The 30 second answer
I scan the string and push every opening bracket onto a stack. A closing bracket must match the most recent opening one, so I pop and compare. If the stack is empty when I need to pop, or a pair does not match, or anything is left on the stack at the end, the string is invalid.
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.
Understanding the prompt 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.
Pattern recognition Stack matching and nesting: push on open, pop and compare on close.
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.
Alternatives 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 "([)]".
Java solution
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
}
}Complexity O(n) time, O(n) extra space in the worst case, for example a string of only openers.
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.
Tests "()" returns true. "()[]{}" returns true. "(]" returns false. "[" returns false. "([)]" returns false.
How to say it in the interview "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."
Sources (3)
- LeetCode 20: Valid Parenthesesleetcode.com
- Java SE 17 API: ArrayDequedocs.oracle.com
- HackerRank: Balanced Bracketshackerrank.com