Bird
Raised Fist0
DSA Cprogramming

Balanced Parentheses Problem Using Stack in DSA C

Choose your learning style10 modes available
Mental Model
We use a stack to keep track of opening brackets and check if each closing bracket matches the last opened one.
Analogy: Imagine stacking plates; each time you see an opening bracket, you put a plate on the stack, and each closing bracket means you remove the top plate and check if it matches.
Stack (top at right): []
Expression: ( [ { } ] )
↑ Start scanning from left to right
Dry Run Walkthrough
Input: expression: "({[]})"
Goal: Check if all parentheses are balanced and correctly nested
Step 1: Read '(' and push it onto the stack
Stack: [ '(' ]
Expression: ( { [ ] } )
           ↑
Why: We store opening brackets to match them later with closing ones
Step 2: Read '{' and push it onto the stack
Stack: [ '(' -> '{' ]
Expression: ( { [ ] } )
             ↑
Why: Keep track of nested opening brackets
Step 3: Read '[' and push it onto the stack
Stack: [ '(' -> '{' -> '[' ]
Expression: ( { [ ] } )
               ↑
Why: Add another opening bracket to stack for matching
Step 4: Read ']' and pop top '[' from stack to match
Stack: [ '(' -> '{' ]
Expression: ( { [ ] } )
                 ↑
Why: Closing bracket matches the last opening bracket
Step 5: Read '}' and pop top '{' from stack to match
Stack: [ '(' ]
Expression: ( { [ ] } )
                   ↑
Why: Closing bracket matches the last opening bracket
Step 6: Read ')' and pop top '(' from stack to match
Stack: []
Expression: ( { [ ] } )
                     ↑
Why: Closing bracket matches the last opening bracket
Result:
Stack: []
All brackets matched correctly -> Balanced
Annotated Code
DSA C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 100

typedef struct Stack {
    char items[MAX];
    int top;
} Stack;

void init(Stack* s) {
    s->top = -1;
}

int isEmpty(Stack* s) {
    return s->top == -1;
}

int isFull(Stack* s) {
    return s->top == MAX - 1;
}

void push(Stack* s, char c) {
    if (!isFull(s)) {
        s->items[++(s->top)] = c;
    }
}

char pop(Stack* s) {
    if (!isEmpty(s)) {
        return s->items[(s->top)--];
    }
    return '\0';
}

int isMatchingPair(char open, char close) {
    return (open == '(' && close == ')') ||
           (open == '{' && close == '}') ||
           (open == '[' && close == ']');
}

int isBalanced(const char* expr) {
    Stack s;
    init(&s);
    for (int i = 0; expr[i] != '\0'; i++) {
        char ch = expr[i];
        if (ch == '(' || ch == '{' || ch == '[') {
            push(&s, ch); // push opening bracket
        } else if (ch == ')' || ch == '}' || ch == ']') {
            if (isEmpty(&s)) {
                return 0; // no matching opening
            }
            char topChar = pop(&s); // pop last opening
            if (!isMatchingPair(topChar, ch)) {
                return 0; // mismatch
            }
        }
    }
    return isEmpty(&s); // balanced if stack empty
}

int main() {
    const char* expr = "({[]})";
    if (isBalanced(expr)) {
        printf("Balanced\n");
    } else {
        printf("Not Balanced\n");
    }
    return 0;
}
push(&s, ch); // push opening bracket
store opening bracket on stack to match later
if (isEmpty(&s)) { return 0; }
if closing bracket found but stack empty, no match possible
char topChar = pop(&s);
pop last opening bracket to check match
if (!isMatchingPair(topChar, ch)) { return 0; }
if popped opening and current closing don't match, fail
return isEmpty(&s);
if stack empty at end, all matched correctly
OutputSuccess
Balanced
Complexity Analysis
Time: O(n) because we scan the expression once, pushing and popping at most once per character
Space: O(n) because in worst case all characters are opening brackets stored in stack
vs Alternative: Compared to counting brackets without stack, this method correctly handles nested and mixed types with linear time and space
Edge Cases
Empty string
Returns balanced because no brackets means nothing to mismatch
DSA C
return isEmpty(&s);
String with only opening brackets
Returns not balanced because stack not empty at end
DSA C
return isEmpty(&s);
String with closing bracket first
Returns not balanced because stack empty when closing bracket found
DSA C
if (isEmpty(&s)) { return 0; }
When to Use This Pattern
When you see a problem asking if brackets or symbols are properly opened and closed in order, use a stack to track openings and match closings.
Common Mistakes
Mistake: Not checking if stack is empty before popping on closing bracket
Fix: Add a check to return false if stack is empty before popping
Mistake: Not verifying that popped opening bracket matches current closing bracket
Fix: Use a function to check matching pairs and return false if mismatch
Summary
Checks if every opening bracket has a matching closing bracket in correct order using a stack
Use when you need to verify balanced and properly nested parentheses or brackets
The key is to push openings on stack and pop to match when a closing bracket appears

Practice

(1/5)
1. What is the main purpose of using a stack in the Balanced Parentheses problem?
easy
A. To keep track of opening parentheses and match them with closing ones
B. To count the total number of parentheses in the expression
C. To reverse the order of parentheses in the expression
D. To store only the closing parentheses encountered

Solution

  1. Step 1: Understand the role of stack in parentheses matching

    A stack helps to remember the last opening parenthesis to match it with the next closing one.
  2. Step 2: Identify why other options are incorrect

    Counting or reversing parentheses does not solve matching pairs; storing only closing parentheses misses the matching logic.
  3. Final Answer:

    To keep track of opening parentheses and match them with closing ones -> Option A
  4. Quick Check:

    Stack tracks openings for matching = B [OK]
Hint: Stack remembers last opening bracket for matching [OK]
Common Mistakes:
  • Thinking stack counts parentheses instead of matching
  • Using stack to store only closing parentheses
  • Ignoring order of parentheses
2. Which of the following code snippets correctly pushes an opening parenthesis '(' onto a stack named stack in C?
easy
A. push(stack, '(');
B. stack.push('(');
C. stack->push('(');
D. push('(', stack);

Solution

  1. Step 1: Recognize typical C stack push syntax

    In C, stack operations are usually functions like push(stack, element).
  2. Step 2: Analyze each option

    push(stack, '('); matches the common C function call syntax. Options B and C use dot or arrow notation typical in C++ or OOP, not plain C. push('(', stack); has arguments reversed.
  3. Final Answer:

    push(stack, '('); -> Option A
  4. Quick Check:

    C stack push syntax = A [OK]
Hint: In C, use push(stack, element) function call [OK]
Common Mistakes:
  • Using C++ style stack.push() in C
  • Reversing arguments in push function
  • Using arrow operator on non-pointer stack
3. What will be the output of the following C code snippet that checks balanced parentheses?
char expr[] = "({[]})";
int result = isBalanced(expr);
printf("%d", result);

Assume isBalanced returns 1 if balanced, 0 otherwise.
medium
A. Runtime error
B. 0
C. Compilation error
D. 1

Solution

  1. Step 1: Analyze the expression "({[]})"

    The expression has matching pairs: '(' with ')', '{' with '}', '[' with ']'. All are properly nested.
  2. Step 2: Understand isBalanced function behavior

    Since the expression is balanced, isBalanced returns 1, so printf prints 1.
  3. Final Answer:

    1 -> Option D
  4. Quick Check:

    Balanced expression returns 1 = A [OK]
Hint: Balanced nested pairs return 1 from isBalanced [OK]
Common Mistakes:
  • Assuming only () pairs are valid
  • Confusing balanced with equal count
  • Expecting 0 for nested but balanced
4. Identify the bug in this C function snippet for checking balanced parentheses:
int isBalanced(char* expr) {
  Stack s;
  for (int i = 0; expr[i] != '\0'; i++) {
    if (expr[i] == '(') push(&s, '(');
    else if (expr[i] == ')') {
      if (isEmpty(&s)) return 0;
      pop(&s);
    }
  }
  return isEmpty(&s);
}
medium
A. Return statement should be inside the loop
B. Stack s is not initialized before use
C. pop() is called without checking if stack is empty
D. The function does not check for other types of brackets

Solution

  1. Step 1: Check stack initialization

    The stack variable 's' is declared but not initialized, so push/pop operations may fail.
  2. Step 2: Verify other parts

    Other options are less critical: checking only () is a limitation but not a bug; pop is called after empty check; return outside loop is correct.
  3. Final Answer:

    Stack s is not initialized before use -> Option B
  4. Quick Check:

    Uninitialized stack causes errors = D [OK]
Hint: Always initialize stack before push/pop [OK]
Common Mistakes:
  • Ignoring stack initialization
  • Assuming pop safe without empty check
  • Thinking return must be inside loop
5. Given the expression "[{()}](({}))", which of the following modifications to the isBalanced function will correctly handle all types of brackets: (), {}, and []?
hard
A. Ignore brackets inside quotes and only check outer brackets
B. Count total opening and closing brackets separately and compare counts
C. Push opening brackets and check matching closing brackets by popping and comparing types
D. Replace all brackets with parentheses before checking

Solution

  1. Step 1: Understand bracket matching logic

    To handle multiple bracket types, push opening brackets and on closing bracket, pop and check if types match.
  2. Step 2: Evaluate other options

    Counting brackets ignores order; ignoring brackets inside quotes is unrelated; replacing brackets loses type info.
  3. Final Answer:

    Push opening brackets and check matching closing brackets by popping and comparing types -> Option C
  4. Quick Check:

    Match types by push/pop for all brackets = C [OK]
Hint: Match each closing bracket with last opening of same type [OK]
Common Mistakes:
  • Counting brackets without order check
  • Ignoring bracket types
  • Replacing brackets loses matching info
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard