← Back to DSA
#20
Valid Parentheses
Valid Parentheses solution for LeetCode 20, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.
Solve on LeetCode ↗Valid Parentheses
Why it belongs on this sheet
This is a fast stack problem that should feel automatic before you move into trickier stateful questions.
Pattern
Expected closing bracket stack
Approach
Push the expected closing bracket for every opening bracket. For a closing bracket, the top of the stack must match it.
Java solution
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(')');
} else if (ch == '{') {
stack.push('}');
} else if (ch == '[') {
stack.push(']');
} else if (stack.isEmpty() || stack.pop() != ch) {
return false;
}
}
return stack.isEmpty();
}
}
Complexity
- Time:
O(n) - Space:
O(n)
Interview note
Pushing expected closers usually reads cleaner than storing openers and matching later.
Dynamic Programming
7 DP Patterns > 100 LeetCode Questions
Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.
7 patternsProgress tracking
Read 7 patterns (5 min)