Valid Parentheses
s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is validValidEvery opening bracket is closed by the same type of bracket, and brackets are closed in the correct order — the most recently opened bracket must be closed first..
An input string is valid if open brackets are closed by the same type of bracket, open brackets are closed in the correct order, and every closing bracket has a corresponding open bracket of the same type.
Test Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ s.length ≤ 10⁴ - ◆
s consists only of the characters '(', ')', '{', '}', '[' and ']'
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
| 1 | class Solution { |
| 2 | public boolean isValid(String s) { |
| 3 | Deque<Character> stack = new ArrayDeque<>(); |
| 4 | Map<Character, Character> pairs = Map.of(')', '(', '}', '{', ']', '['); |
| 5 | for (char c : s.toCharArray()) { |
| 6 | if (c == '(' || c == '{' || c == '[') { |
| 7 | stack.push(c); |
| 8 | } else { |
| 9 | if (stack.isEmpty() || stack.pop() != pairs.get(c)) return false; |
| 10 | } |
| 11 | } |
| 12 | return stack.isEmpty(); |
| 13 | } |
| 14 | } |
| 15 |
Create an empty stack. We'll push every opening bracket we see, and pop to check closing brackets against it.
Approach & Solutions
Brute Force — Repeated Removal
BruteRepeatedly scan the string for an adjacent matching pair — "()", "{}", or "[]" — and remove it, shrinking the string. If the string can be whittled all the way down to empty, every bracket had a partner in the right place. Each pass is O(n), and up to n/2 passes may be needed, so this costs O(n²) overall.
O(n²)O(n)1class Solution {
2 public boolean isValid(String s) {
3 while (s.contains("()") || s.contains("{}") || s.contains("[]")) {
4 s = s.replace("()", "").replace("{}", "").replace("[]", "");
5 }
6 return s.isEmpty();
7 }
8}Optimal — Stack
OptimalWalk through the string once. Every opening bracket gets pushed onto a stack. Every closing bracket must match whatever is currently on top of the stack — if it does, pop it and move on; if it doesn't (or the stack is empty), the string is invalid immediately. At the end, the string is valid only if the stack is empty — every opener found its closer, in the right order.
O(n)O(n)1class Solution {
2 public boolean isValid(String s) {
3 Deque<Character> stack = new ArrayDeque<>();
4 Map<Character, Character> pairs = Map.of(')', '(', '}', '{', ']', '[');
5 for (char c : s.toCharArray()) {
6 if (c == '(' || c == '{' || c == '[') {
7 stack.push(c);
8 } else {
9 if (stack.isEmpty() || stack.pop() != pairs.get(c)) return false;
10 }
11 }
12 return stack.isEmpty();
13 }
14}