← Back to DSA Course | Chapter 5: Stacks | Lesson 3 of 5

Balanced Parentheses चेक करना

Balanced parentheses जांचने जैसा है कि हर opening bracket को सही order में अपना खुद का closing partner मिले, यह याद रखने के लिए कि कौन अब भी इंतज़ार कर रहा है एक stack उपयोग करते हुए।
Syntax
markup
stack = []
for ch in expression:
    if ch in opening:
        stack.append(ch)
    elif not stack or stack.pop() != matching[ch]:
        return False
return not stack

Parentheses Matching

यह जांचना कि किसी expression में brackets balanced हैं या नहीं, जैसे हर ( को एक ) से और हर [ को एक ] से match करना, एक classic problem है जिसे एक stack इसके LIFO ordering के कारण साफ़ तरीके से solve करता है।

उदाहरण: Parentheses Matching

#include <iostream>
#include <stack>
using namespace std;
int main() {
    string expr = "([{}])";
    stack<char> s;
    cout << "checking " << expr << " for balance using a stack" << endl;
    return 0;
}
public class Main {
    public static void main(String[] args) {
        String expr = "([{}])";
        System.out.println("checking " + expr + " for balance using a stack");
    }
}
expr = "([{}])"
print("checking", expr, "for balance using a stack")
#include <stdio.h>
int main() {
    char *expr = "([{}])";
    printf("checking %s for balance using a stack\n", expr);
    return 0;
}

Opening and Closing Brackets

Algorithm हर opening bracket जो मिले उसे stack पर push करता है, और जब भी यह एक closing bracket पर आता है, यह जांचता है कि stack का top matching opening type है, अगर हो तो इसे pop करते हुए।

उदाहरण: Opening and Closing Brackets

#include <iostream>
#include <stack>
using namespace std;
int main() {
    string expr = "(a[b]{c})";
    stack<char> s;
    for (char ch : expr) {
        if (ch == '(' || ch == '[' || ch == '{') s.push(ch);
        else if (ch == ')' || ch == ']' || ch == '}') {
            if (!s.empty()) s.pop();
        }
    }
    cout << "stack size after scan: " << s.size() << endl;
    return 0;
}
import java.util.Stack;
public class Main {
    public static void main(String[] args) {
        String expr = "(a[b]{c})";
        Stack<Character> s = new Stack<>();
        for (char ch : expr.toCharArray()) {
            if (ch == '(' || ch == '[' || ch == '{') s.push(ch);
            else if (ch == ')' || ch == ']' || ch == '}') {
                if (!s.isEmpty()) s.pop();
            }
        }
        System.out.println("stack size after scan: " + s.size());
    }
}
expr = "(a[b]{c})"
s = []
for ch in expr:
    if ch in "([{":
        s.append(ch)
    elif ch in ")]}":
        if s:
            s.pop()
print("stack size after scan:", len(s))
#include <stdio.h>
#include <string.h>
int main() {
    char *expr = "(a[b]{c})";
    char s[20]; int top = -1;
    for (int i = 0; i < strlen(expr); i++) {
        char ch = expr[i];
        if (ch == '(' || ch == '[' || ch == '{') s[++top] = ch;
        else if (ch == ')' || ch == ']' || ch == '}') { if (top >= 0) top--; }
    }
    printf("stack size after scan: %d\n", top + 1);
    return 0;
}

Balanced Expressions

एक expression सिर्फ तब balanced है जब हर opening bracket आखिरकार सही order में बंद हो और पूरी expression scan होने के बाद stack पूरी तरह खाली हो जाए।

उदाहरण: Balanced Expressions

#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 == ')' && (s.empty() || s.top() != '(')) return false;
        else if (ch == ')') s.pop();
    }
    return s.empty();
}
int main() {
    cout << "([)] balanced: " << isBalanced("([)]") << endl;
    cout << "(())  balanced: " << isBalanced("(())") << endl;
    return 0;
}
import java.util.Stack;
public class Main {
    static boolean isBalanced(String expr) {
        Stack<Character> s = new Stack<>();
        for (char ch : expr.toCharArray()) {
            if (ch == '(') s.push(ch);
            else if (ch == ')') {
                if (s.isEmpty() || s.pop() != '(') return false;
            }
        }
        return s.isEmpty();
    }
    public static void main(String[] args) {
        System.out.println("([)] balanced: " + isBalanced("([)]"));
        System.out.println("(()) balanced: " + isBalanced("(())"));
    }
}
def is_balanced(expr):
    s = []
    for ch in expr:
        if ch == "(":
            s.append(ch)
        elif ch == ")":
            if not s or s.pop() != "(":
                return False
    return not s

print("([)] balanced:", is_balanced("([)]"))
print("(()) balanced:", is_balanced("(())"))
#include <stdio.h>
#include <string.h>
int isBalanced(char *expr) {
    char s[20]; int top = -1;
    for (int i = 0; i < strlen(expr); i++) {
        if (expr[i] == '(') s[++top] = expr[i];
        else if (expr[i] == ')') {
            if (top < 0) return 0;
            top--;
        }
    }
    return top == -1;
}
int main() {
    printf("(()) balanced: %d\n", isBalanced("(())"));
    return 0;
}

Stack-Based Validation

यह exact pattern technical interviews में लगातार दिखता है, क्योंकि यह test करता है कि आप एक असली problem को LIFO ordering पर map कर सकते हैं या नहीं, और यह JSON या HTML tags जैसे nested structures validate करने तक generalize करता है।

उदाहरण: Stack-Based Validation

#include <iostream>
#include <stack>
using namespace std;
bool isBalanced(string expr) {
    stack<char> s;
    for (char ch : expr) {
        if (ch == '{' || ch == '[') s.push(ch);
        else if ((ch == '}' && (s.empty() || s.top() != '{')) ||
                 (ch == ']' && (s.empty() || s.top() != '['))) return false;
        else if (ch == '}' || ch == ']') s.pop();
    }
    return s.empty();
}
int main() {
    cout << "{\"a\": [1,2,3]} balanced: " << isBalanced("{[]}") << endl;
    return 0;
}
import java.util.Stack;
public class Main {
    static boolean isBalanced(String expr) {
        Stack<Character> s = new Stack<>();
        for (char ch : expr.toCharArray()) {
            if (ch == '{' || ch == '[') s.push(ch);
            else if (ch == '}' || ch == ']') {
                if (s.isEmpty()) return false;
                s.pop();
            }
        }
        return s.isEmpty();
    }
    public static void main(String[] args) {
        System.out.println("JSON-like {[]} balanced: " + isBalanced("{[]}"));
    }
}
def is_balanced(expr):
    s = []
    for ch in expr:
        if ch in "{[":
            s.append(ch)
        elif ch in "}]":
            if not s:
                return False
            s.pop()
    return not s

print("JSON-like {[]} balanced:", is_balanced("{[]}"))
#include <stdio.h>
#include <string.h>
int isBalanced(char *expr) {
    char s[20]; int top = -1;
    for (int i = 0; i < strlen(expr); i++) {
        if (expr[i] == '{' || expr[i] == '[') s[++top] = expr[i];
        else if (expr[i] == '}' || expr[i] == ']') { if (top < 0) return 0; top--; }
    }
    return top == -1;
}
int main() {
    printf("JSON-like {[]} balanced: %d\n", isBalanced("{[]}"));
    return 0;
}

Parentheses Practice

अच्छी practice में edge cases शामिल हैं जैसे match करने के लिए stack पर कुछ न होने के साथ एक unmatched closing bracket, गलत order में बंद brackets (जैसे ([)]), और एक string जो stack पर अब भी unclosed brackets के साथ खत्म होती है।

उदाहरण: Parentheses Practice

#include <iostream>
#include <stack>
using namespace std;
bool isBalanced(string expr) {
    stack<char> s;
    for (char ch : expr) {
        if (ch == '(') s.push(ch);
        else if (ch == ')') {
            if (s.empty()) return false;
            s.pop();
        }
    }
    return s.empty();
}
int main() {
    cout << ") balanced: " << isBalanced(")") << endl;
    cout << "(( balanced: " << isBalanced("((") << endl;
    return 0;
}
import java.util.Stack;
public class Main {
    static boolean isBalanced(String expr) {
        Stack<Character> s = new Stack<>();
        for (char ch : expr.toCharArray()) {
            if (ch == '(') s.push(ch);
            else if (ch == ')') {
                if (s.isEmpty()) return false;
                s.pop();
            }
        }
        return s.isEmpty();
    }
    public static void main(String[] args) {
        System.out.println(") balanced: " + isBalanced(")"));
        System.out.println("(( balanced: " + isBalanced("(("));
    }
}
def is_balanced(expr):
    s = []
    for ch in expr:
        if ch == "(":
            s.append(ch)
        elif ch == ")":
            if not s:
                return False
            s.pop()
    return not s

print(") balanced:", is_balanced(")"))
print("(( balanced:", is_balanced("(("))
#include <stdio.h>
#include <string.h>
int isBalanced(char *expr) {
    char s[20]; int top = -1;
    for (int i = 0; i < strlen(expr); i++) {
        if (expr[i] == '(') s[++top] = expr[i];
        else if (expr[i] == ')') { if (top < 0) return 0; top--; }
    }
    return top == -1;
}
int main() {
    printf(") balanced: %d\n", isBalanced(")"));
    printf("(( balanced: %d\n", isBalanced("(("));
    return 0;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक closing bracket पर यह जांचे बिना stack से pop करना कि यह खाली नहीं है, इसलिए ")" crash होता है।
  2. सिर्फ brackets count करना उनका type और order जांचने के बजाय, इसलिए "([)]" balanced दिखता है।
  3. Loop खत्म होने पर यह जांचे बिना true return करना कि stack खाली है, इसलिए "((" pass हो जाता है।
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.