Problem
Given a string of the characters '(', ')', '{', '}', '[' and ']', return true if the brackets are closed in the correct order and every opener has a matching closer.
Original: LeetCode 20: Valid Parentheses.
Examples
Example 1
`s = "()"``true`Example 2
`s = "()[]{}"``true`Example 3
`s = "(]"``false`Example 4
`s = "["``false`Example 5
`s = "([)]"``false`Constraints
1 <= s.length <= 10^4sconsists of parentheses only'()[]{}'.
Hints
Hint 1
The last unclosed opener must be the first one to close, which is exactly a stack. Interleaving such as "([)]" is invalid even though each type has a pair. An empty string is valid; a single opener is not.
Hint 2
Stack matching and nesting: push on open, pop and compare on close.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Repeatedly search for and remove adjacent matching pairs until nothing changes: O(n²).
Optimal. Walk the string once with a Deque used as a stack. Openers go on the stack. A closer pops; if the stack is empty or the popped opener does not match, return false. At the end the stack must be empty. ArrayDeque is the right Java stack: java.util.Stack is a synchronized leftover.
Alternative. HackerRank Balanced Brackets is the same problem with the same stack. A counter is enough only when there is a single bracket type, because it cannot detect "([)]".
Complexity
- Time
- O(n)
O(n) time, O(n) extra space in the worst case, for example a string of only openers.
- Space
- O(n)
Code
import java.util.ArrayDeque;
public class ValidParentheses {
static boolean isValid(String s) {
var st = new ArrayDeque<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(' || c == '[' || c == '{') st.push(c);
else if (st.isEmpty() || !matches(st.pop(), c)) return false;
}
return st.isEmpty();
}
static boolean matches(char open, char close) {
return (open == '(' && close == ')')
|| (open == '[' && close == ']')
|| (open == '{' && close == '}');
}
public static void main(String[] args) {
System.out.println(isValid("()")); // true
System.out.println(isValid("()[]{}")); // true
System.out.println(isValid("(]")); // false
System.out.println(isValid("[")); // false
System.out.println(isValid("([)]")); // false
}
}Edge cases
- "()" and "()[]{}" are valid.
- A mismatch such as "(]" or an interleave such as "([)]" is invalid.
- A leftover opener, as in "[", is invalid.
Follow-ups
- Minimum Remove to Make Valid Parentheses, when the string also contains letters and you must delete the fewest brackets.
- Generate Parentheses, which is backtracking, not a stack walk.
Interview script
"I push opening brackets and, on a closer, I pop and check that it matches the most recent opener. If I cannot pop, or a pair is wrong, or the stack is not empty at the end, the string is invalid. Linear time."
Source: LeetCode 20: Valid Parentheses Source: Java SE 17 API: ArrayDeque Source: HackerRank: Balanced Brackets
Sources (3)
- LeetCode 20: Valid Parenthesesleetcode.com
- Java SE 17 API: ArrayDequedocs.oracle.com
- HackerRank: Balanced Bracketshackerrank.com