Valid Parentheses in Python: From Brute Force to Stack

Tags:

Easy · Stack · Strings · LeetCode 20. Imagine checking whether every opened box is closed in reverse order. A stack remembers the most recently opened bracket.

Stack walkthrough: ([{}]) — push three openers, then pop three matching closers.

1. Problem and constraints

Given a string containing only (), [], and {}, return true if each opening bracket is closed by the same type in the correct order. Length: 1 to 10,000.

Examples: ()[]{} → True; ([{}]) → True; (] → False; ([)] → False.

2. Progressive hints

Hint 1: Adjacent matching pairs can be removed. Hint 2: The last opening bracket must close first. Hint 3: Use a LIFO stack.

3. Brute-force approach

Repeatedly remove adjacent matching pairs. If no more pairs can be removed, the string is valid exactly when empty.

def valid_brute(s):
while any(pair in s for pair in (“()”, “[]”, “{}”)):
for pair in (“()”, “[]”, “{}”):
s = s.replace(pair, “”)
return not s

4. Optimized stack approach

Push opening brackets. For a closing bracket, reject an empty stack or mismatched top. Accept only if the stack is empty at the end.

FOR each character:
IF opening: PUSH
ELSE IF stack empty or POP does not match: RETURN false
RETURN stack is emptydef is_valid(s):
stack = []
pairs = {“)”: “(“, “]”: “[“, “}”: “{“}
for ch in s:
if ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
else:
stack.append(ch)
return not stack

5. Dry run: ([{}])

Read ( → stack (. Read [ → stack ([. Read { → stack ([{. Read } → stack ([. Read ] → stack (. Read ) → empty. Result: True.

6. Why it works

Invariant: after every successful step, the stack holds exactly the unmatched opening brackets in encounter order. A closing bracket must match the latest unmatched opener. A mismatch cannot be repaired by later characters. At the end, an empty stack means all brackets matched.

7. Complexity comparison

Repeated replacement: O(n²) worst-case time, O(n) auxiliary space for intermediate strings. Stack: O(n) time and O(n) worst-case auxiliary space. Every character is processed once.

8. Edge cases and testing

Test single opener, single closer, nested pairs, adjacent pairs, crossed pairs, odd lengths and deeply nested inputs. Empty input is outside the stated constraints but both functions return True.

assert is_valid(“([{}])”)
assert is_valid(“()[]{}”)
assert not is_valid(“([)]”)
assert not is_valid(“]”)
assert not is_valid(“(“)

9. Common mistakes

Do not count brackets without checking order. Do not pop an empty stack. Do not forget to check for leftover openers.

10. Interview questions

Why a stack? Matching follows last-in-first-out. Can a counter replace it? Only for one bracket type with prefix validation. Can we do better than O(n) time? No, worst-case input must be inspected. What is worst-case stack size? n for all opening brackets. How to return the first error? Track indices alongside opening brackets.

11. Related practice

Valid Parentheses · Min Stack · Longest Valid Parentheses · Two Sum in Python

12. Quick revision

Recognize nested matching as a stack problem. Push openers, match and pop closers, reject mismatches, and require an empty stack at the end.

Categories

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *