Valid Parentheses
Easy
Topics
Given a string s containing just ()[]{}, determine if the input is valid: brackets are closed by the same type in the correct order.
Example 1
Every bracket closes the most recently opened one of the same kind, so the answer is
true. Counting brackets is not enough — ([)] has balanced counts and is still invalid, which is why the order a stack enforces matters.Cells are the characters of the string; the small numbers underneath are indices.
Input: s = "()[]{}"
Output: true
Example 2
The shaded bracket is the failure: either it closes the wrong kind, or it is never closed at all. Both are caught by a stack — push openers, and on a closer check the top matches before popping.
Input: s = "([)]" Output: false
Constraints
- 1 <= s.length <= 10^4
- s consists of brackets only.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Brackets must close in the reverse order they open: the most recently opened bracket must be the first one closed. "Last opened, first closed" is the definition of a stack (LIFO).
So we push every opening bracket and, on every closing bracket, verify it matches the bracket on top of the stack.
Approach
- Maintain a stack of unmatched opening brackets.
- For an opening bracket, push it.
- For a closing bracket, the top of the stack must be its matching open — if the stack is empty or the top is wrong, the string is invalid.
- At the end, the stack must be empty; leftover opens mean unclosed brackets.
Walkthrough
s = "([])"
( push stack=[ (
[ push stack=[ ( [
] top=[ ok stack=[ (
) top=( ok stack=[]
end: stack empty -> validComplexity
- Time — O(n): each character is pushed and popped at most once.
- Space — O(n): a string of all opening brackets fills the stack.
Common Pitfalls
- Forgetting the final empty-stack check accepts strings like
"(". - A closing bracket when the stack is empty (e.g.
")") must return false, not crash.
Full Solution — all languages
class Solution:
def isValid(self, s):
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
for c in s:
if c in pairs:
if not stack or stack.pop() != pairs[c]:
return False
else:
stack.append(c)
return not stackimport java.util.*;
class Solution {
public boolean isValid(String s) {
Map<Character, Character> pairs = new HashMap<>();
pairs.put(')', '(');
pairs.put(']', '[');
pairs.put('}', '{');
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (pairs.containsKey(c)) {
if (stack.isEmpty() || stack.pop() != pairs.get(c)) return false;
} else {
stack.push(c);
}
}
return stack.isEmpty();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool isValid(string s) {
unordered_map<char, char> pairs {
{
')', '('
},
{
']', '['
},
{
'}', '{'
}
};
vector<char> stack;
for (char c : s) {
if (pairs.count(c)) {
if (stack.empty() || stack.back() != pairs[c]) return false;
stack.pop_back();
} else {
stack.push_back(c);
}
}
return stack.empty();
}
};/**
* @param {string} s
* @return {boolean}
*/ var isValid = function(s) {
const pairs = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const c of s) {
if (pairs[c]) {
if (stack.pop() !== pairs[c]) return false;
} else {
stack.push(c);
}
}
return stack.length === 0;
};