Valid Parentheses
Difficulty: Easy · Pattern: Stack & Monotonic Stack · LeetCode #20
s consists only of the characters ()[]{}. Return true if every bracket is closed by the same type of bracket in the correct order (properly nested), and nothing is left unclosed.
Examples
text
"{[()]}" → true
"([)]" → false (crossed)
"((" → false (unclosed)
"()[]{}" → trueHints
- The most recently opened bracket must be the first one closed. That's last-in, first-out.
- On a closing bracket, the stack top must be its matching opener.
- At the end, the stack must be empty.
Approach
Push every opening bracket. For a closing bracket, the stack must be non-empty and its top must be the matching opener; pop it. Any mismatch means invalid. After processing all characters, the string is valid only if the stack is empty (nothing left unclosed).
Complexity
Time: O(n). Space: O(n) in the worst case (all openers).
Python solution
def isValid(s):
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
for ch in s:
if ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
else:
stack.append(ch)
return not stackJavaScript solution
function isValid(s) {
const pairs = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const ch of s) {
if (ch in pairs) {
if (!stack.length || stack.pop() !== pairs[ch]) return false;
} else stack.push(ch);
}
return stack.length === 0;
}