Valid Parentheses
Easy · Stack
Jump to codeGiven a string made of (), [] and {}, decide whether every opener has a matching closer in the correct nested order. The empty string is valid.
Examples
Example 1
s = "()"
Output: true
Example 2
s = "()[]{}"Output: true
Constraints
- 1 <= s.length <= 10^4
- s consists only of parentheses characters ()[]{}
Need a hint?
The next closing bracket must match the most recent unmatched opener.
Asked in real interviews
Candidates reported versions of Valid Parentheses from these company interviews. Some company questions are locked and open with Premium or XP.
- Validate Properly Nested BracketsAmazon
- Solve tree equality and valid parenthesesDeutsche Bank
- Validate a String of BracketsGarner Health
Solution approach
Push opening brackets onto a stack. For a closing bracket, reject an empty stack or a mismatched top; otherwise pop. Accept only if the stack is empty at the end, since leftover openers are unmatched.
Complexity
O(n) time and O(n) space.
Python reference solution
def isValid(s):
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
for char in s:
if char in pairs:
if not stack or stack.pop() != pairs[char]:
return False
else:
stack.append(char)
return not stack
JavaScript solution
function isValid(s) {
const pairs = {')': '(', ']': '[', '}': '{'};
const stack = [];
for (const c of s) {
if (c in pairs) {
if (stack.pop() !== pairs[c]) return false;
} else stack.push(c);
}
return stack.length === 0;
}
Java solution
import java.util.*;
class Solution {
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(') stack.push(')');
else if (c == '[') stack.push(']');
else if (c == '{') stack.push('}');
else if (stack.isEmpty() || stack.pop() != c) return false;
}
return stack.isEmpty();
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> expected;
for (char c : s) {
if (c == '(') expected.push(')');
else if (c == '[') expected.push(']');
else if (c == '{') expected.push('}');
else {
if (expected.empty() || expected.top() != c) return false;
expected.pop();
}
}
return expected.empty();
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[ "()" ]
true
[
"()[]{}"
]true
[ "(]" ]
false
[
"("
]false
[
"{[]}"
]true
Drafts are saved per language in this browser when storage is available.