×

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

C++ Fibonacci Series

What is a Fibonacci series? A Fibonacci series or sequence is a very popular programming paradigm. The next element occurring in the N terms series is determined by the sum of...

2 minutes read.

C++ Program to Print Fibonacci Triangle

Fibonacci Triangle Program in CPP Definition: Fibonacci Triangle as the name suggests is the same as the Fibonacci number series where the next element is the sum of the previous two elements....

3 minutes read.

Dynamic Memory Allocation in C++

In some programming situations, the number of data items changes as the program is running, which is known as dynamic data or input. Consider a real-world situation where a program...

3 minutes read.

C++ cin and cout

In this article, we will discuss the C++ cin and cout with their library and examples. C++ Standard Input/Output: User-program communication is made possible by C++’s usage of input and output (I/O)...

5 minutes read.

Do-While Loop Examples in C++

Before we move on the examples of Do-While loop, let’s learn little bit about the Do-While loop in C++ language. Do While loop An iterative loop that checks the condition at the...

5 minutes read.

Decimal to Hexadecimal in C++

We need to write a program in C++ that converts a decimal number into an equal hexadecimal number given a decimal value as input i.e. convert a number having a...

2 minutes read.

How the value is passed in C++

Introduction: The call-by-value method of giving arguments to a function duplicates the real value of an argument into the formal parameter of the function. In this instance, modifications to the parameter...

5 minutes read.

Containership in C++

In C++, it is possible to create an object in one class into another class, and that object is a member of another class. This relationship is known as a...

4 minutes read.

Inheritance and Friendship in C++

In this tutorial, we will look into what Inheritance and Friendship in C++ are, as well as the differences between the two. What is Inheritance in C++: In C++, inheritance is an...

2 minutes read.

Message Passing in C++

The act of sending and receiving information by an object is referred to as communication, and all communication between objects that takes place via message is known as message passing....

1 minute read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

C++ Forward Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is...

3 minutes read.

What does Buffer Flush mean in C++

A buffer flush, to explain simple layman's terms, is nothing but the transfer of computer data which is being stored in a rentable temporary memory of your computer running either...

3 minutes read.

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...

2 minutes read.

Two dimension array

C++ Two dimension (2D) Array Two dimension (2D) array is an array of arrays. It is represented in the form of row and column. The elements of 2D array are accessed through the...

2 minutes read.

Palindrome Number Program in C++

A palindrome number is one that is the same when it is reversed. Palindrome numbers include 22, 33, 44, 55, 66, 77, 88, and 99. Algorithm for Palindrome Numbers Get the user's...

4 minutes read.

Storage Classes in C

Storage Classes in C Storage Classes are used to define the variable and function property. These functionalities include basically the scope, accessibility, and lifetime that help us detect the existence of...

4 minutes read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

C++ Inheritance

What do you mean by Inheritance ? The ability to define new classes based on existing classes in order to reuse and organise code is referred to as inheritance. Single inheritance...

7 minutes read.