Valid Parentheses
Determine if a string of bracket characters has every opener closed by the same type in proper nested order using a stack of expected closers.
01The problem
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
| Input | Output | Why |
|---|---|---|
"()[]{}" | true | Every opener is matched immediately by its corresponding closer |
"(]" | false | Round opener '(' is closed by square bracket ']' |
"([)]" | false | Out of order: '[' was opened after '(', so it must close first |
Constraints: 1 <= s.length <= 10^4, string consists solely of parentheses '()[]{}'.
02How to spot it
- The problem demands that the most recently opened bracket must be the first one closed.
- This is textbook Last In, First Out (LIFO) ordering.
- Nesting can be arbitrarily deep.
- An opener creates an expectation: when we see
'(', we expect a')'. Pushing the expected closer onto a stack turns matching into a single equality check.
So: stack of expected closers.
03Pseudocode
stack = empty
for c in s:
if c is an opener: push its closer
elif stack empty or pop() != c:
return false
return stack is empty- See an opener? Remember which closer you now expect.
- See a closer? It must match the latest expectation at the top of the stack.
- At the end, nothing may remain open.
04Watch it work
s
expected closers (top on right)
Initialize an empty stack. As we read openers, we push the matching closer we expect.
Pseudocode
- stack = empty
- for c in s:
- if c is an opener: push its closer
- elif stack empty or pop() != c:
- return false
- return stack is empty
Variables
- stack
05Step-by-step dry run
- 1
s
(0)1[2]3{4}5expected closers (top on right)
Initialize an empty stack. As we read openers, we push the matching closer we expect.
stack =
- 2
s
(0)1[2]3{4}5cexpected closers (top on right)
)0topSaw opener `(`. Push expected closer `)` onto the stack.
c = (expected = )stackSize = 1
- 3
s
(0)1[2]3{4}5cexpected closers (top on right)
Saw closer `)` matching expected `)`. Popped successfully.
c = )matched = )stackSize = 0
- 4
s
(0)1[2]3{4}5cexpected closers (top on right)
]0topSaw opener `[`. Push expected closer `]` onto the stack.
c = [expected = ]stackSize = 1
- 5
s
(0)1[2]3{4}5cexpected closers (top on right)
Saw closer `]` matching expected `]`. Popped successfully.
c = ]matched = ]stackSize = 0
- 6
s
(0)1[2]3{4}5cexpected closers (top on right)
}0topSaw opener `{`. Push expected closer `}` onto the stack.
c = {expected = }stackSize = 1
- 7
s
(0)1[2]3{4}5cexpected closers (top on right)
Saw closer `}` matching expected `}`. Popped successfully.
c = }matched = }stackSize = 0
- 8
s
(0)1[2]3{4}5expected closers (top on right)
Finished scanning. Stack is empty: all brackets matched and closed properly. Return true.
valid = true
06Java solution
import java.util.ArrayDeque;
import java.util.Deque;
public class ValidParentheses {
public static boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(') stack.push(')');
else if (c == '[') stack.push(']');
else if (c == '{') stack.push('}');
else if (stack.isEmpty() || stack.pop() != c) return false;
}
return stack.isEmpty();
}
public static void main(String[] args) {
System.out.println(isValid("()[]{}"));
System.out.println(isValid("([)]"));
}
}true false
07Why it works
Pushing the expected closer instead of the opener simplifies the verification step. When we see '(', we push ')'. When a closing character c arrives:
- If the stack is empty, there is no opener waiting for this closer (e.g.
")"). Returnfalse. - If
stack.pop() != c, the most recently opened scope was closed by the wrong type (e.g."(]"). Returnfalse. - If they match, the inner scope is cleanly resolved.
After examining all characters, any remaining element on the stack indicates an unclosed opener (e.g. "((("). Checking stack.isEmpty() handles this edge case.
08Time and space
- Time complexity:
O(n). We iterate through the string of lengthnonce. Each character triggers at most onepushorpop, bothO(1)operations. - Space complexity:
O(n). In the worst case (e.g."(((((("), the stack holdsnexpected closer characters.
09Edge cases
- Odd length string: Immediately invalid (cannot be evenly paired).
- String starting with closer (e.g.
")("): First character hitsstack.isEmpty(), immediately returningfalse. - All openers (e.g.
"((("): Loop finishes with non-empty stack,stack.isEmpty()correctly returnsfalse. - Single character (e.g.
"["): Stack has 1 element, returnsfalse.
10Common mistakes
- Using counters instead of a stack. A simple counter tracks quantity, but fails on ordering (e.g.
"([)]"has equal counts of each type, but invalid nesting). - Using legacy
java.util.Stack.StackextendsVector, which synchronizes every method call and slows down execution. UseArrayDeque. - Forgetting the final
stack.isEmpty()check. Returningtrueat the end of the loop without checking whether the stack is empty wrongly accepts incomplete strings like"(()".
11Other approaches
| Approach | Time | Space | Use when |
|---|---|---|---|
| Stack of expected closers | O(n) | O(n) | Standard, optimal interview solution |
Replace "()", "[]", "{}" in string | O(n^2) | O(n) | Quick to write in a script, unacceptable in interview |
12In the interview
13Check your understanding
Quiz · 2 questions
0 of 2 answered
1. Why does pushing the expected closing bracket make the code cleaner?
2. What happens when evaluating the string "([)]"?
14Solve it yourself
Try implementing a function that also returns the 0-based index of the first invalid bracket:
- Push an object or pair
(expectedCloser, index)onto the stack. - Return the offending index if mismatch occurs, or the index of the first unclosed opener if the stack remains non-empty.