Valid Parentheses (LeetCode 20): Solution and Explanation

Easy
String
Stack

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Create an empty list stack and a map mapping = {')': '(', '}': '{', ']': '['}.
  2. Iterate over each character char in s.
  3. If char is a closing bracket (a key in mapping), check that the stack is non-empty and stack[-1] == mapping[char]. If so, pop; otherwise return False.
  4. If char is an opening bracket, push it onto the stack.
  5. After the loop, return not stack, which is true only when every opener was matched.

Step-by-step example

s = "{[]}("
  1. '{' is an opener, push it. Stack = ['{'].
  2. '[' is an opener, push it. Stack = ['{', '['].
  3. ']' is a closer whose opener is '['. The top is '[', so pop. Stack = ['{'].
  4. '}' maps to '{', which matches the top, so pop. Stack = [].
  5. '(' is pushed. Stack = ['('].
  6. 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 stack

Time and space complexity

Time

O(n)

Each character is processed once with a constant time map lookup and at most one push or pop.

Space

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 True at 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.