Valid Parentheses
Pattern: Balanced brackets
Push every opener. A closer must match the opener on top of the stack, which is then popped; a closer with an empty stack or the wrong opener means invalid. At the end the stack must be empty.
The problem
Given a string of the characters ()[]{}, return whether it is valid: every opener is closed by the same kind, in
the right order, and every closer has an opener. "()[]{}" is valid; "(]" and "([)]" are not.
Think first
- Which opener must the next closer match?
- What if a closer arrives with nothing open?
- What if openers are left at the end?
Hints
Brute force, and why it fails
Repeatedly delete (), [] and {} until nothing changes, then check for an empty string: O(n²).
The key insight
Nesting means the last opened is the first closed, which is what a stack gives.
Dry run
{0
[1
s = "{[]}". Push { and [.
Step 1 of 4
The plan
for c in s:
if c is an opener: push c
elif stack empty or pop() is not the partner of c: return false
return stack is empty
Complexity
- Time
O(n)- Space
O(n)
One pass; the stack can hold every character in the worst case.
Edge cases
- A single closer: false.
- Only openers: false.
- Odd length: always false.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public boolean isValid(String s) {
Deque<Character> st = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') st.push(c); // an opener waits for its closer
else {
if (st.isEmpty()) return false; // a closer with nothing to close
char open = st.pop();
if ((c == ')' && open != '(') || (c == ']' && open != '[') || (c == '}' && open != '{')) return false;
}
}
return st.isEmpty(); // every opener must be closed
}
}C++
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for (char c : s) {
if (c == '(' || c == '[' || c == '{') st.push(c); // an opener waits for its closer
else {
if (st.empty()) return false; // a closer with nothing to close
char open = st.top();
st.pop();
if ((c == ')' && open != '(') || (c == ']' && open != '[') || (c == '}' && open != '{')) return false;
}
}
return st.empty(); // every opener must be closed
}
};Python
class Solution:
def isValid(self, s: str) -> bool:
pairs = {")": "(", "]": "[", "}": "{"}
st = []
for c in s:
if c in "([{":
st.append(c) # an opener waits for its closer
elif not st or st.pop() != pairs[c]:
return False # nothing to close, or the wrong kind
return not st # every opener must be closedCommon mistakes
- Forgetting the final empty check.
- Popping an empty stack.