Skip to content

Valid Parentheses

EasyLeetCode #20Time O(n)Space O(n)

You get a string made only of (, ), [, ], { and }. It is valid if every opener is closed by the same type of bracket, and brackets close in the right order.

"()[]{}" -> true
"([)]" -> false (the ) arrives while [ is still the newest open bracket)

Counting brackets is not enough: ([)] has the right counts but is invalid. What matters is order. A closer must match the most recently opened bracket that is still open. “Most recent unfinished thing” is exactly what a stack gives you.

Walk the string. Push each opener (the Python and TypeScript code stores the opener, the Java code stores the closer it expects, which is the same idea). On a closer, the stack must be non-empty and its top must match, otherwise the string is invalid. At the end the stack must be empty, or some opener was never closed.

Show solutionHide solution
def is_valid(s: str) -> bool:
pairs = {")": "(", "]": "[", "}": "{"} # closer -> its opener
stack = []
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 # leftover openers mean unmatched
  • Time: O(n) — each character is pushed or popped at most once.
  • Space: O(n) — a string of only openers, like ((((, fills the stack.
  • Popping an empty stack. A string like ] starts with a closer. Check the stack is non-empty first (the not stack or guard).
  • Forgetting the final check. "((" never fails during the loop. Return stack is empty, not True.
  • Odd length is an instant false. You can add that as a quick exit, but it is only an optimization; the stack logic is still needed.

Minimum Remove to Make Valid Parentheses (LeetCode 1249)

Section titled “Minimum Remove to Make Valid Parentheses (LeetCode 1249)”

Remove the fewest ( or ) characters so the string becomes valid, and return it. The trick: use the stack to hold the indices of unmatched (. An unmatched ) (empty stack) is marked for removal immediately. Whatever indices remain on the stack at the end are the unmatched (. Drop all marked indices.

Find the length of the longest valid substring of ( and ). The trick: keep indices on the stack, starting with a sentinel -1. On ) pop; if the stack is empty push the current index as the new boundary, otherwise the length is i - stack[-1]. O(n).

Build all valid strings of n pairs. The trick: not a stack problem but the same validity rule. Use backtracking, tracking how many ( you have opened and only adding ) while closers are fewer than openers.