Bird
Raised Fist0
DSA Cprogramming~10 mins

Balanced Parentheses Problem Using Stack in DSA C - Execution Trace

Choose your learning style10 modes available
Concept Flow - Balanced Parentheses Problem Using Stack
Start
↓
Read next character
↓
Is it an opening bracket?
Yes→Push to stack
↓
Stack updated
↓
Is it a closing bracket?
Yes→Is stack empty?
↓
Pop from stack
↓
Ignore other chars
↓
Stack updated
↓
More characters?
Yes→Repeat
↓
End
↓
Is stack empty?
Yes→Balanced
The flow reads each character, pushes opening brackets onto the stack, pops for matching closing brackets, and checks stack emptiness at the end to decide balance.
Execution Sample
DSA C
#include <stdio.h>
#include <string.h>
#define MAX 100

int isBalanced(char *expr) {
    char stack[MAX];
    int top = -1;
    for (int i = 0; expr[i] != '\0'; i++) {
        char c = expr[i];
        if (c == '(' || c == '{' || c == '[') {
            stack[++top] = c;
        } else if (c == ')' || c == '}' || c == ']') {
            if (top == -1) return 0;
            char topChar = stack[top--];
            if ((c == ')' && topChar != '(') ||
                (c == '}' && topChar != '{') ||
                (c == ']' && topChar != '['))
                return 0;
        }
    }
    return top == -1;
}
This code checks if the input string has balanced parentheses using a stack.
Execution Table
StepOperationCurrent CharStack BeforeStack AfterPointer ChangesVisual State
1Read char((top: -1 -> 0( ) -> ( )
2Push((((top: 0 -> 1( ( )
3Read char)(((top: 1 -> 0( )
4Pop and match)(((top: 1 -> 0( )
5Read char[(([top: 0 -> 1( [ )
6Push[([([top: 1 -> 1( [ )
7Read char]([(top: 1 -> 0( )
8Pop and match]([(top: 1 -> 0( )
9Read char{(({top: 0 -> 1( { )
10Push{({({top: 1 -> 1( { )
11Read char}({(top: 1 -> 0( )
12Pop and match}({(top: 1 -> 0( )
13End of string((top: 0( )
14Check stack empty((top: 0Stack not empty - Unbalanced
💡 Stack not empty at end means parentheses are unbalanced.
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 5After Step 7After Step 9After Step 11Final
top-10010100
stack"""(""(""([""(""({""(""("
Key Moments - 3 Insights
Why do we push only opening brackets onto the stack?
Because opening brackets mark places where we expect matching closing brackets later. This is shown in execution_table steps 1, 5, and 9 where '(' '[' '{' are pushed.
What happens if we find a closing bracket but the stack is empty?
It means there is no matching opening bracket, so the expression is unbalanced. This is checked in the code and would cause an immediate return 0, as seen in execution_table step 4 if top was -1.
Why do we check if the stack is empty at the end?
If the stack is not empty, it means some opening brackets were never matched. Execution_table step 14 shows this final check.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5, what is the stack content after reading '['?
A"(("
B"(["
C"("
D"["
💡 Hint
Refer to the 'Stack After' column in execution_table row 5.
At which step does the stack pointer 'top' first return to 0 after being incremented?
AStep 11
BStep 7
CStep 3
DStep 14
💡 Hint
Check variable_tracker for 'top' values after each step.
If the input string ended after step 11, what would the final stack state be?
AStack with one '('
BEmpty stack
CStack with one '{'
DStack with '(' and '{'
💡 Hint
Look at execution_table step 13 and variable_tracker final stack content.
Concept Snapshot
Balanced Parentheses Using Stack:
- Push opening brackets onto stack.
- On closing bracket, pop and check match.
- If mismatch or empty stack on pop, unbalanced.
- At end, stack empty means balanced.
- Use stack pointer 'top' to track stack state.
Full Transcript
This visualization shows how to check balanced parentheses using a stack. We read each character of the input string. When we see an opening bracket like '(', '{', or '[', we push it onto the stack. When we see a closing bracket like ')', '}', or ']', we check if the stack is empty. If empty, it means no matching opening bracket, so the string is unbalanced. Otherwise, we pop the top of the stack and check if it matches the closing bracket. If it does not match, the string is unbalanced. After processing all characters, if the stack is empty, the parentheses are balanced; if not, they are unbalanced. The execution table shows each step with the stack content and pointer changes. The variable tracker shows how the stack pointer 'top' and stack content change over time. Key moments clarify why we push only opening brackets, what happens if the stack is empty on closing bracket, and why we check stack emptiness at the end. The quiz tests understanding of stack content and pointer changes at specific steps.

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