
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check for Balanced Parenthesis Using Stacks in C++
In this article, we will learn how to check for a balanced parentheses using stack data structure in C++ program. First of all let's understand what is balanced parentheses.
A string of parentheses is said to be balanced parentheses, If
- Every opening bracket has corresponding closing bracket of same type.
- The brackets are closed in correct order.
For an example, we can say that the expression [{} () {()}] it is balanced. But {[}] is not balanced eventhough it contains opening and closing brackets of same type.
In this problem, you are provided with a string containing different types of opening and closing brackets. Your task is is to specify if it is balanced or not. For example,
Input: exp = "[()]{}{[()()]()}" Output: Balanced Input: exp = "[(])" Output: Not Balanced
Algorithm: Check Balanced Parentheses Using Stack
Following are steps to check for balanced parentheses in a string,
- Step 1: Create an empty stack.
- Step 2: Traverse the given string from left to right.
- Step 3: For each character in the string, run step 4 and step 5.
- Step 4: If the character is an opening bracket (ie, (,{,[ ), push it onto stack.
- Step 5: If the character is a closing bracket (ie, ),},] ), and if the stack is empty return false. Else, Pop the top of the stack and check if it matches the correct opening bracket. If it does'nt match return false.
- Step 6: After the traversal, if the stack is empty return true (ie, Balanced), Otherwise return false (ie, Not Balanced).
C++ Code: Check Balanced Parentheses Using Stack
The code below shows implementation of above algorithm using C++ programming language.
#include <iostream> #include <stack> using namespace std; bool isBalanced(string expr) { stack<char> s; for (char ch : expr) { if (ch == '(' || ch == '{' || ch == '[') { s.push(ch); } else if (ch == ')' || ch == '}' || ch == ']') { if (s.empty()) return false; char top = s.top(); s.pop(); if ((ch == ')' && top != '(') || (ch == '}' && top != '{') || (ch == ']' && top != '[')) { return false; } } } return s.empty(); } int main() { string input="{()]}" if (isBalanced(input)) cout << "Balanced parentheses" << endl; else cout << "Unbalanced parentheses" << endl; return 0; }
The output of the above code will be:
Unbalanced parentheses
Time and Space Complexity
The time and space complexity of above algorithm is:
- Time Complexity: O(n), Where n in length of input string
- Space Complexity: O(n), Due to the extra stack space we used in program.