Balanced Parentheses Problem Using Stack in DSA C# - Time & Space Complexity
We want to know how the time needed to check balanced parentheses grows as the input string gets longer.
How does the number of steps change when the input size increases?
Analyze the time complexity of the following code snippet.
public bool IsBalanced(string s) {
Stack<char> stack = new Stack<char>();
foreach (char c in s) {
if (c == '(') {
stack.Push(c);
} else if (c == ')') {
if (stack.Count == 0) return false;
stack.Pop();
}
}
return stack.Count == 0;
}
This code checks if parentheses in a string are balanced using a stack.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character in the string once.
- How many times: Exactly once for each character (n times for string length n).
As the input string gets longer, the number of steps grows directly with its length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The steps increase in a straight line as input size increases.
Time Complexity: O(n)
This means the time to check balanced parentheses grows linearly with the input size.
[X] Wrong: "The time complexity is quadratic because of the stack operations inside the loop."
[OK] Correct: Each stack operation (push/pop) takes constant time, so they don't multiply the loop's time; the loop still runs once per character.
Understanding this linear time check helps you solve many real problems involving matching pairs efficiently.
"What if we changed the input to include multiple types of brackets (like {}, [], ())? How would the time complexity change?"
Practice
Balanced Parentheses Problem?Solution
Step 1: Understand the role of stack in parentheses matching
A stack helps keep track of opening parentheses so that each closing parenthesis can be matched correctly in order.Step 2: Identify why other options are incorrect
Counting or reversing parentheses does not solve the matching problem, and sorting is unrelated to balance checking.Final Answer:
To keep track of opening parentheses and match them with closing ones -> Option BQuick Check:
Stack tracks openings for matching closings [OK]
- Thinking stack counts parentheses instead of matching
- Confusing stack with queue for this problem
- Assuming stack reverses parentheses order
stack?Solution
Step 1: Recall stack method to add elements
In C#, the method to add an element to a stack isPush().Step 2: Identify incorrect methods
Add()andInsert()are not stack methods;Enqueue()is for queues.Final Answer:
stack.Push('('); -> Option AQuick Check:
Use Push() to add to stack [OK]
- Using queue methods like Enqueue() on stack
- Trying to use Add() or Insert() which don't exist for stack
- Confusing stack with list methods
string input = "({[]})";
Stack<char> stack = new Stack<char>();
foreach (char c in input) {
if (c == '(' || c == '{' || c == '[') {
stack.Push(c);
} else {
if (stack.Count == 0) {
Console.WriteLine("Unbalanced");
return;
}
char top = stack.Pop();
if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) {
Console.WriteLine("Unbalanced");
return;
}
}
}
if (stack.Count == 0) Console.WriteLine("Balanced"); else Console.WriteLine("Unbalanced");Solution
Step 1: Trace the input string character by character
Opening brackets '(', '{', '[' are pushed onto the stack. Closing brackets pop and check matching. The input "({[]})" is perfectly nested.Step 2: Check stack emptiness after processing
After processing all characters, stack is empty, so output is "Balanced".Final Answer:
Balanced -> Option DQuick Check:
All pairs matched, stack empty = Balanced [OK]
- Not checking stack empty before popping
- Mismatching bracket pairs
- Ignoring stack emptiness at end
Stack<char> stack = new Stack<char>();
foreach (char c in input) {
if (c == '(' || c == '{' || c == '[') {
stack.Push(c);
} else {
char top = stack.Pop();
if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) {
return false;
}
}
}
return stack.Count == 0;Solution
Step 1: Check for stack underflow before popping
The code pops from stack without checking if it's empty, which can cause runtime error if closing bracket appears first.Step 2: Confirm matching logic is correct
Matching pairs are correctly checked, and return false if mismatch occurs.Final Answer:
Missing check if stack is empty before Pop() -> Option CQuick Check:
Always check stack empty before Pop() [OK]
- Popping from empty stack causing exceptions
- Ignoring stack.Count == 0 before Pop()
- Confusing Push and Pop methods
"[{()}]({[]})", which of the following modifications to the balanced parentheses algorithm will correctly handle this input and return true?Options:
A) Ignore all characters except parentheses.
B) Use a stack and match pairs as usual.
C) Use two stacks, one for opening and one for closing parentheses.
D) Use a queue instead of a stack to track parentheses.
Solution
Step 1: Understand the input and algorithm
The input contains only parentheses characters. The standard stack-based matching algorithm works for nested and sequential pairs.Step 2: Evaluate each option's correctness
Use a stack and match pairs as usual. is correct as it uses the standard stack approach. Ignore all characters except parentheses. is irrelevant since input has only parentheses. Use two stacks, one for opening and one for closing parentheses. complicates unnecessarily. Use a queue instead of a stack to track parentheses. fails because queue does not track last opening bracket.Final Answer:
Use a stack and match pairs as usual. -> Option AQuick Check:
Standard stack method handles nested pairs [OK]
- Trying to use queue which breaks matching order
- Overcomplicating with multiple stacks
- Ignoring characters that are not parentheses
Ready to prove it?
Pass the test and this pattern moves unknown
