Balanced Parentheses Problem Using Stack in DSA C - Time & Space Complexity
We want to know how the time to check balanced parentheses grows as the input string gets longer.
Specifically, how many steps does it take to verify if parentheses are balanced?
Analyze the time complexity of the following code snippet.
bool isBalanced(char* expr) {
Stack s = createStack();
for (int i = 0; expr[i] != '\0'; i++) {
if (expr[i] == '(') {
push(&s, '(');
} else if (expr[i] == ')') {
if (isEmpty(&s)) return false;
pop(&s);
}
}
return isEmpty(&s);
}
This code checks if parentheses in a string are balanced using a stack.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop through each character of the input string once.
- How many times: Exactly once for each character (n times for input length n).
Each character is checked once, so the steps grow directly with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and stack operations |
| 100 | About 100 checks and stack operations |
| 1000 | About 1000 checks and stack operations |
Pattern observation: Operations increase linearly as input size increases.
Time Complexity: O(n)
This means the time to check balanced parentheses grows in direct proportion to the input length.
[X] Wrong: "The time complexity is higher because of stack operations inside the loop."
[OK] Correct: Each stack operation (push/pop) takes constant time, so they do not add extra loops or multiply the steps.
Understanding this linear time check helps you handle many real-world problems involving matching pairs efficiently.
"What if we also had to check for multiple types of brackets like {}, [], and ()? How would the time complexity change?"
Practice
Solution
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.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.Final Answer:
To keep track of opening parentheses and match them with closing ones -> Option AQuick Check:
Stack tracks openings for matching = B [OK]
- Thinking stack counts parentheses instead of matching
- Using stack to store only closing parentheses
- Ignoring order of parentheses
stack in C?Solution
Step 1: Recognize typical C stack push syntax
In C, stack operations are usually functions like push(stack, element).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.Final Answer:
push(stack, '('); -> Option AQuick Check:
C stack push syntax = A [OK]
- Using C++ style stack.push() in C
- Reversing arguments in push function
- Using arrow operator on non-pointer stack
char expr[] = "({[]})";
int result = isBalanced(expr);
printf("%d", result);Assume
isBalanced returns 1 if balanced, 0 otherwise.Solution
Step 1: Analyze the expression "({[]})"
The expression has matching pairs: '(' with ')', '{' with '}', '[' with ']'. All are properly nested.Step 2: Understand isBalanced function behavior
Since the expression is balanced, isBalanced returns 1, so printf prints 1.Final Answer:
1 -> Option DQuick Check:
Balanced expression returns 1 = A [OK]
- Assuming only () pairs are valid
- Confusing balanced with equal count
- Expecting 0 for nested but balanced
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);
}Solution
Step 1: Check stack initialization
The stack variable 's' is declared but not initialized, so push/pop operations may fail.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.Final Answer:
Stack s is not initialized before use -> Option BQuick Check:
Uninitialized stack causes errors = D [OK]
- Ignoring stack initialization
- Assuming pop safe without empty check
- Thinking return must be inside loop
"[{()}](({}))", which of the following modifications to the isBalanced function will correctly handle all types of brackets: (), {}, and []?Solution
Step 1: Understand bracket matching logic
To handle multiple bracket types, push opening brackets and on closing bracket, pop and check if types match.Step 2: Evaluate other options
Counting brackets ignores order; ignoring brackets inside quotes is unrelated; replacing brackets loses type info.Final Answer:
Push opening brackets and check matching closing brackets by popping and comparing types -> Option CQuick Check:
Match types by push/pop for all brackets = C [OK]
- Counting brackets without order check
- Ignoring bracket types
- Replacing brackets loses matching info
Ready to prove it?
Pass the test and this pattern moves unknown
