C Program
#include <stdio.h> char s[100];int t=-1; void push(char c){s[++t]=c;} char pop(){return s[t--];} int main(){ char e[]="{[()]}"; for(int i=0;e[i];i++) if(e[i]=='('||e[i]=='['||e[i]=='{') push(e[i]); else{ char c=pop(); if((e[i]==')'&&c!='(')||(e[i]==']'&&c!='[')||(e[i]=='}'&&c!='{')){ printf("Not Balanced");return 0; } } printf(t==-1?"Balanced":"Not Balanced"); }
C Output
Balanced
C++ Program
#include <bits/stdc++.h> using namespace std; int main(){ string e="{[()]}"; stack<char> st; for(char c:e){ if(c=='('||c=='['||c=='{') st.push(c); else{ if(st.empty()||(c==')'&&st.top()!='(')||(c==']'&&st.top()!='[')||(c=='}'&&st.top()!='{')){ cout<<"Not Balanced";return 0; } st.pop(); } } cout<<(st.empty()?"Balanced":"Not Balanced"); }
C++ Output
Balanced
JAVA Program
import java.util.*; class Main{ public static void main(String[] a){ String e="{[()]}"; Stack<Character> st=new Stack<>(); for(char c:e.toCharArray()){ if(c=='('||c=='['||c=='{') st.push(c); else if(st.isEmpty()||(c==')'&&st.pop()!='(')||(c==']'&&st.pop()!='[')||(c=='}'&&st.pop()!='{')){ System.out.println("Not Balanced");return; } } System.out.println(st.isEmpty()?"Balanced":"Not Balanced"); } }
JAVA Output
Balanced
Python Program
e="{[()]}" st=[] for c in e: if c in "([{": st.append(c) else: if not st or {')':'(',']':'[','}':'{'}[c]!=st.pop(): print("Not Balanced"); break else: print("Balanced" if not st else "Not Balanced")
Python Output
Balanced
Detailed Explanation
Example
Consider the string {[()]}. Every opening symbol has a corresponding closing symbol in the right order. The matching is similar to closing boxes: the very last box you opened is the first one you need to close. This "last in, first out" is why we employ a stack.
Real-Life Analogy
Think about stacking dinner plates. You set down a red plate, followed by a blue plate, followed by a green plate. If the reader asks you to put it away, you'll put the green one away first, then the blue, and finally the red. The same is true with parentheses. The last that you opened must be the first to close. If you close them in the wrong order, it's like grabbing a plate from in the middle of the stack — everything falls down.
Step-by-Step Logic
When we read a character:
If it is an opening bracket (, [, or {, we push it onto the stack.
If it is a closing bracket ), ], or }, we pop the top of the stack and compare it to see if it matches.
If at any time we pop from an empty stack or the popped bracket does not match the current closing bracket, the parentheses are unbalanced.
At the end, if the stack is empty, the string is balanced; otherwise, it’s not.
Why It Matters
Balanced parentheses checking is one of the simplest and most practical parsing problems. It appears in compiler design, HTML/XML validation, mathematical expression validation, and anywhere nesting rules must be followed. If you’ve ever forgotten to close a tag in HTML or a bracket in code, you’ve encountered this problem.
Learning Insights
You learn stacks, which are ubiquitous for a great many parsing problems. You also observe how to cope with matching pairs and find early errors before having to process the whole string. The reasoning also supports the idea that some problems naturally fit into particular data structures.
Common Mistakes
Beginners tend to miss the test for an empty stack before popping, resulting in runtime errors. Another frequent mistake is failing to check at the end whether the stack is empty — a string such as "((( would incorrectly be reported as balanced without such a check.
Real-World Applications
This reasoning is employed in:
IDEs and code editors for color marking matching brackets.
HTML/XML tag validation in web browsers.
Syntax checking in compilers for programming languages.
Text processing utilities that work with nested data structures such as JSON.
Interview Hints
Interviewers can mix this with processing quotes, escape sequences, or more than one type of delimiters. They may also provide you with a stream of characters rather than a preloaded string, making you consider real-time processing.
SEO-Friendly Conclusion
Balanced parentheses checking via a stack is a basic algorithm that is the basis for most parsing and syntax checking duties in software programming. From the construction of compilers to HTML/XML parsing, understanding how a stack is used to provide matching opening and closing brackets is a must-have skill for every programmer. Getting mastery over this algorithm enhances problem-solving abilities, solidifies data structure skills, and gets you ready for coding interviews as well as real-world projects.
Social Plugin