Valid Parentheses
The problem
Section titled “The problem”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)Key insight
Section titled “Key insight”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 unmatchedexport function isValid(s: string): boolean { const pairs: Record<string, string> = { ')': '(', ']': '[', '}': '{' }; // closer -> its opener const stack: string[] = []; for (const ch of s) { if (ch in pairs) { if (stack.length === 0 || stack.pop() !== pairs[ch]) return false; } else { stack.push(ch); } } return stack.length === 0; // leftover openers mean unmatched}import java.util.ArrayDeque;import java.util.Deque;
class Solution { public boolean isValid(String s) { Deque<Character> stack = new ArrayDeque<>(); for (char ch : s.toCharArray()) { if (ch == '(') stack.push(')'); // push the closer we expect else if (ch == '[') stack.push(']'); else if (ch == '{') stack.push('}'); else if (stack.isEmpty() || stack.pop() != ch) return false; } return stack.isEmpty(); // leftover openers mean unmatched }}Complexity
Section titled “Complexity”- Time: O(n) — each character is pushed or popped at most once.
- Space: O(n) — a string of only openers, like
((((, fills the stack.
Watch out for
Section titled “Watch out for”- Popping an empty stack. A string like
]starts with a closer. Check the stack is non-empty first (thenot stack orguard). - Forgetting the final check.
"(("never fails during the loop. Returnstack is empty, notTrue. - 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.
Variations
Section titled “Variations”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.
Longest Valid Parentheses (LeetCode 32)
Section titled “Longest Valid Parentheses (LeetCode 32)”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).
Generate Parentheses (LeetCode 22)
Section titled “Generate Parentheses (LeetCode 22)”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.