×

Check for Balanced Brackets in an Expression (well-formedness) using Stack

Write a program that check the correctness of the pairs and ordering of the characters “{“, “}”, “(“, “)”, “[“, “]” in the expression string exp.

Example:

Checking for balanced parenthesis is one of the most important tasks of a compiler.
int main () {
	for ( int i = 0; i < 10; i ++ ) {
		// Some code
	}
  }
}    <----The Compiler generates an error.

Algorithm:

  • Consider a character stack to Sp.
  • Go over the exp expression string presently.
  • Push the character to the stack if it is a starting bracket (‘(‘ or ‘{‘ or ‘[‘).
  • If the currently displayed character is a closing bracket (‘)’ or ‘}’ or ‘]’), pop it from the stack; if it is the corresponding opening bracket, everything is OK; otherwise, the brackets are not balanced.
  • If some initial brackets remain in the stack upon traversal, the balance is "not balanced."

The implementation of the aforementioned concept is seen below:

C Program:

#include <stdio.h>
#include <stdlib.h>
#define bool int


struct spNode {
	char data;
	struct spNode* next;
};
void push ( struct spNode** top_ref, int newdata );
int pop ( struct spNode** topref );
bool istheMatchingPair ( char character01, char character02 )
{
	if ( character01 == '(' && character02 == ')')
		return 1;
	else if ( character01 == '{' && character02 == '}' )
		return 1;
	else if ( character01 == '[' && character02 == ']' )
		return 1;
	else
		return 0;
}
bool aretheBracketsBalanced ( char exp [] )
{
	int i = 0;


	struct spNode* stack = NULL;


	while ( exp [i] )
	{
		if ( exp [i] == '{' || exp [i] == '(' || exp [i] == '[' )
			push ( & stack, exp [i] );


		if ( exp [i] == '}' || exp [i] == ')'
			|| exp[i] == ']' ) {


			if ( stack == NULL )
				return 0;


			else if ( !istheMatchingPair ( pop ( & stack ), exp [i] ) )
				return 0;
		}
		i++;
	}
	if ( stack == NULL )
		return 1; // balanced
	else
		return 0; // not balanced
}
int main ()
{
	char exp [100] = "{()}[]";
	if ( aretheBracketsBalanced (exp) )
		printf ("Balanced \n" );
	else
		printf ( "Not Balanced \n" );
	return 0;
}
void push ( struct spNode** topref, int newdata )
{
	struct spNode* newnode
		= ( struct spNode* ) malloc ( sizeof ( struct spNode ) );
	if ( newnode == NULL ) {
		printf ( "Stack overflow n" );
		getchar ();
		exit (0);
	}
	newnode -> data = newdata;
	newnode -> next = ( *topref );
	( *topref ) = newnode;
}
int pop ( struct spNode** topref )
{
	char res;
	struct spNode* top;
	if ( *topref == NULL ) {
		printf ( "Stack overflow n" );
		getchar ();
		exit (0);
	}
	else {
		top = *topref;
		res = top -> data;
		*topref = top -> next;
		free (top);
		return res;
	}
}

C++ Program:

#include <bits/stdc++.h>
using namespace std;


bool aretheBracketsBalanced ( string exp )
{
	stack<char> temp;
		for ( int i = 0; i < exp.length (); i++ )
		{
			if ( temp.empty() )
			{
				temp.push ( exp [i] );
			}
			else if ( ( temp.top() =='('&& exp [i]==')') || ( temp.top ()=='{' && exp [i] =='}') || ( temp.top () =='[' && exp [i]==']' ) )
			{
				temp.pop ();
			}
			else
			{
				temp.push ( exp [i] );
			}
		}
		if ( temp.empty () )
		{
			return true;
		}
		return false;
}
int main ()
{
	string exp = "{()}[]";
	if ( aretheBracketsBalanced (exp) )
		cout << "Balanced";
	else
		cout << "Not Balanced";
	return 0;
}

Output:

Balanced

Time Complexity: O(n)

Space Complexity: O(n) for stack.


Related Topics

CPP Templates

C++ provides a powerful feature called template, which allows the definition of generic classes and generic functions. Generic programming is a technique where different algorithms work in communion by using...

4 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.

Multilevel Inheritance

C++ Multilevel Inheritance Multilevel inheritance is such an inheritance in which a derived class is created from another derived class. C++ Multilevel Inheritance Example In this example, a base class Student is inherited in...

2 minutes read.

Random Number Generator in C++

In programming, we need to frequently create the randomly. For example, a dice game, handing out cards to players, apps for rearranging tunes, etc. T There are two tools available in...

4 minutes read.

C++ Object Class

C++ Object Class Overview: C++ is a high-level programming language and an object-oriented programming language. An object-oriented language always has some properties of classes and objects. In this article, we...

4 minutes read.

Passing a Vector to a function in C++

A pointer is sent to the function when we feed it an array. However, there are two ways to pass a vector: Pass by Value Pass by Reference A copy of a vector...

3 minutes read.

Decltype type Specifier in C++

The primary use of C++ decltype is to inspect the declaration type of an entity in an expression. The auto keyword can declare a particular type of variable, whereas the...

4 minutes read.

C++ Encapsulation

The following two essential components are present in all C++ programmes: Functions are the parts of a programme that perform actions, and they are termed programme statements (code).Program data is the...

4 minutes read.

Splitting a string in C++

Any programming language must have the ability to work with string data. For programming needs, we sometimes need to separate string data. Many computer languages provide a split() method that...

4 minutes read.

Armstrong number using for loop in C++

What is For Loop? A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax that can be...

4 minutes read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

Stringstream in C++ and its applications

In this tutorial, we will explore what the stringstream in C++ is. We will also learn its application. What is stringstream? With the aid of a stringstream, user can read from a...

2 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

Array of Object in C++

What is an Array? In C++, an array is a group of related data types, such as int, char, float, double, etc., that are easily accessed by index value alone and...

12 minutes read.

Octal to Decimal in C++

We need to write a system that converts octal number into equal decimal number when octal number is given as input. Let us look at an example of a program in...

2 minutes read.

Pointers in C++

Pointers are a powerful feature in the C++ programming language, allowing developers to directly manipulate memory addresses and create more efficient and dynamic programs. However, pointers can also source various...

3 minutes read.

Vector in C++

Vector in C++ In today’s article, we will be learning all the things about vector in C++ and how vector is different form an array in C++. So basically, vector is very...

3 minutes read.

C++ Close file

C++ File Handling close() Function A file which is opened while reading or writing in file handling must be closed after performing an action on it. The close() function is used to close...

2 minutes read.