Valid Parentheses (LeetCode 20): Solution and Explanation
Given a string made only of the characters ( ) { } [ ], decide whether every bracket is closed by the same type of bracket and in the correct order. Every closing bracket must match the most recent unmatched opening bracket.
Watch it run step by step
Try your own input and write the code →Intuition
If there were only one kind of bracket, a single counter would do: add one for (, subtract one for ), fail if the counter ever goes negative, and succeed if it ends at zero. With three kinds that breaks down. The string ([)] has balanced counts for every type, yet it is invalid, because the ) arrives while the most recently opened bracket is [.
That phrase, "the most recently opened bracket", is the key. Brackets nest, so the one that must close next is always the last one opened that has not been closed yet. A data structure that gives you the most recent unmatched item is a stack. Push each opening bracket. When a closing bracket arrives, look at the top of the stack: if it is the matching opener, pop it, because that pair is done. If the stack is empty or the top is a different opener, the string is invalid right there.
When the scan ends, there is one last check. Any openers still on the stack were never closed, so the string is valid only if the stack is empty. A dictionary from each closing bracket to its opener keeps the matching logic to a single lookup instead of a chain of conditionals, and it also doubles as the test for whether a character is a closer.
Approach: Stack with a bracket map
- Create an empty list
stackand a mapmapping = {')': '(', '}': '{', ']': '['}. - Iterate over each character
charins. - If
charis a closing bracket (a key inmapping), check that the stack is non-empty andstack[-1] == mapping[char]. If so, pop; otherwise returnFalse. - If
charis an opening bracket, push it onto the stack. - After the loop, return
not stack, which is true only when every opener was matched.
Step-by-step example
s = "{[]}("- '{' is an opener, push it. Stack = ['{'].
- '[' is an opener, push it. Stack = ['{', '['].
- ']' is a closer whose opener is '['. The top is '[', so pop. Stack = ['{'].
- '}' maps to '{', which matches the top, so pop. Stack = [].
- '(' is pushed. Stack = ['('].
- The scan ends with one unmatched opener on the stack, so the function returns False. Without the final '(' it would return True.
Code: Python, Java, C++
1class Solution:
2 def isValid(self, s: str) -> bool:
3 stack = []
4 mapping = {")": "(", "}": "{", "]": "["}
5
6 for char in s:
7 if char in mapping:
8 if stack and stack[-1] == mapping[char]:
9 stack.pop()
10 else:
11 return False
12 else:
13 stack.append(char)
14
15 return not stack1class Solution {
2 public boolean isValid(String s) {
3 Stack<Character> stack = new Stack<>();
4
5 for (char c : s.toCharArray()) {
6 if (c == '(') stack.push(')');
7 else if (c == '{') stack.push('}');
8 else if (c == '[') stack.push(']');
9 else if (stack.isEmpty() || stack.pop() != c)
10 return false;
11 }
12 return stack.isEmpty();
13 }
14}1class Solution {
2public:
3 bool isValid(string s) {
4 stack<char> stack;
5 for (char c : s) {
6 if (c == '(') stack.push(')');
7 else if (c == '{') stack.push('}');
8 else if (c == '[') stack.push(']');
9 else {
10 if (stack.empty() || stack.top() != c) return false;
11 stack.pop();
12 }
13 }
14 return stack.empty();
15 }
16};Time and space complexity
O(n)
Each character is processed once with a constant time map lookup and at most one push or pop.
O(n)
In the worst case, such as a string of only opening brackets, every character is pushed onto the stack.
Other approaches
Repeated pair removal (time O(n²), space O(n))
Keep replacing the substrings "()", "[]" and "{}" with empty strings until nothing changes, then check whether the string is empty. It is easy to understand but each pass rescans and rebuilds the string.
Push expected closers (time O(n), space O(n))
When you see an opener, push the closer you expect instead. A closing bracket is then valid only if it equals the popped value. It is the same stack algorithm with a slightly different comparison and identical complexity.
Common mistakes
- Returning
Trueat the end without checking that the stack is empty. A string like "((" never fails a match but is still invalid. - Reading
stack[-1]without first checking that the stack is non-empty. A string starting with a closer, such as "]", would crash instead of returning false. - Using three separate counters, one per bracket type. Counters cannot detect wrong nesting like "([)]".
- Short-circuiting on odd length is a valid optimization, but forgetting that an even length string can still be invalid. Length alone proves nothing beyond parity.
Frequently asked questions
Why use a stack for Valid Parentheses?
Brackets must close in the reverse order they opened, which is last in, first out. A stack keeps the most recent unmatched opener on top, exactly where the next closer needs to look.
Can Valid Parentheses be solved without a stack?
With only one bracket type, a counter is enough. With multiple types you need to remember the order of openers, so some form of stack is required for a linear time solution.
What is the time and space complexity?
O(n) time because each character is pushed or popped at most once, and O(n) space in the worst case when every character is an opener.
Is an empty string valid?
Yes. There are no unmatched brackets, the stack stays empty, and the function returns true.