Balanced Parentheses Problem Using Stack in DSA Python - Time & Space Complexity
We want to know how the time needed to check balanced parentheses changes as the input string grows.
How does the number of steps grow when the string gets longer?
Analyze the time complexity of the following code snippet.
def is_balanced(s: str) -> bool:
stack = []
pairs = {')': '(', ']': '[', '}': '{'}
for char in s:
if char in '([{':
stack.append(char)
elif char in ')]}':
if not stack or stack.pop() != pairs[char]:
return False
return not stack
This code checks if the parentheses in the string are balanced using a stack.
- 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 string gets longer, the number of steps grows directly with the number of characters.
| 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: The work grows in a straight line with input size.
Time Complexity: O(n)
This means the time to check balanced parentheses grows linearly with the length of the string.
[X] Wrong: "Because of the stack operations, the time complexity is more than linear, maybe quadratic."
[OK] Correct: Each character is processed once, and stack push/pop are constant time, so total time stays linear.
Understanding this linear time check shows you can analyze how data structures like stacks help solve problems efficiently.
"What if we checked for balanced parentheses without using a stack, by scanning multiple times? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem goal
The Balanced Parentheses problem checks if all opening brackets like '(' have a matching closing bracket ')' in the correct order.Step 2: Role of stack in checking
A stack helps track opening brackets and ensures each one is closed properly in sequence.Final Answer:
Whether every opening bracket has a matching closing bracket in correct order -> Option AQuick Check:
Balanced parentheses = matching pairs in order [OK]
- Thinking it checks string length
- Confusing with character types
- Ignoring order of brackets
Solution
Step 1: Recall Python list methods for stack
Python uses list to implement stack; to add an element on top, use append().Step 2: Check each option
add() and push() are not list methods; insert() adds at specific index, not top.Final Answer:
stack.append(x) -> Option BQuick Check:
Use append() to push in Python stack [OK]
- Using push() which is not a Python list method
- Using add() which is for sets
- Using insert() without index
def is_balanced(s):
stack = []
for char in s:
if char == '(': stack.append(char)
elif char == ')':
if not stack: return False
stack.pop()
return not stack
print(is_balanced('(()())'))
print(is_balanced('(()'))Solution
Step 1: Trace first input '(()())'
Push '(' three times, pop ')' three times, stack empty at end, returns True.Step 2: Trace second input '(()'
Push '(' twice, one ')' pops one '(', stack not empty at end, returns False.Final Answer:
True\nFalse -> Option AQuick Check:
Balanced string returns True, unbalanced returns False [OK]
- Not checking stack empty at end
- Returning true too early
- Ignoring unmatched openings
def check_balance(s):
stack = []
for ch in s:
if ch == '(': stack.push(ch)
elif ch == ')':
if stack == []: return False
stack.pop()
return len(stack) == 0
Solution
Step 1: Identify stack method error
Python list has no push() method; append() should be used to add elements.Step 2: Verify other parts
Return statements and empty checks are correct; pop() after check is correct.Final Answer:
stack.push(ch) is invalid; use stack.append(ch) instead -> Option CQuick Check:
Use append() to add in Python list stack [OK]
- Using push() instead of append()
- Checking stack emptiness incorrectly
- Calling pop() without checking stack
s = '{[()()]}', which modification is needed in the balanced parentheses stack algorithm to correctly check this string?Solution
Step 1: Identify bracket types in string
The string contains curly braces {}, square brackets [], and parentheses ().Step 2: Modify algorithm for multiple bracket types
The stack algorithm must track each opening bracket type and match it with the correct closing bracket type.Final Answer:
Add support for multiple types of brackets and match pairs accordingly -> Option DQuick Check:
Match bracket types correctly for balanced check [OK]
- Checking only parentheses and ignoring others
- Using queue instead of stack
- Counting brackets without matching
Ready to prove it?
Pass the test and this pattern moves unknown
