31. Valid Parentheses
s contains only the characters ()[]{}. It is valid when every opening bracket is closed by the same type of bracket, in the correct order.
Example 1
Input:
s = "()[]{}"Output:
trueExample 2
Input:
s = "(]"Output:
falseHint 1
The most recent unclosed bracket must be closed first: last in, first out.
Approach 1: Stack ✅
Push openers; on a closer, pop and check the type.
⏱ Time O(n)💾 Space O(n)
Reference solution for Stack (time O(n), space O(n)). Each solution passes every test in all four languages.
class Solution:
def isValid(self, s: str) -> bool:
pair = {')': '(', ']': '[', '}': '{'}
stack = []
for ch in s:
if ch in pair:
if not stack or stack.pop() != pair[ch]:
return False # wrong or missing opener
else:
stack.append(ch)
return not stack # nothing left unclosedclass Solution {
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char ch : s.toCharArray()) {
if (ch == '(' || ch == '[' || ch == '{') stack.push(ch);
else {
if (stack.isEmpty()) return false;
char open = stack.pop();
if ((ch == ')' && open != '(') || (ch == ']' && open != '[') || (ch == '}' && open != '{')) return false;
}
}
return stack.isEmpty();
}
}class Solution {
public:
bool isValid(string s) {
stack<char> st;
for (char ch : s) {
if (ch == '(' || ch == '[' || ch == '{') st.push(ch);
else {
if (st.empty()) return false;
char open = st.top(); st.pop();
if ((ch == ')' && open != '(') || (ch == ']' && open != '[') || (ch == '}' && open != '{')) return false;
}
}
return st.empty();
}
};function isValid(s) {
const pair = { ')': '(', ']': '[', '}': '{' }, stack = [];
for (const ch of s) {
if (ch in pair) { if (stack.pop() !== pair[ch]) return false; }
else stack.push(ch);
}
return stack.length === 0;
}Try solving it yourself first. Interviewers care more about how you explain the approach than about the finished code.
Watch the core idea of this problem step by step. Change the input and press Visualize.
Explained in the lesson Stacks, Queues & Monotonic Stacks.
Run your code to see results here.