Problem
Section titled “Problem”Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()"Output: trueExample 2:
Input: s = "()[]{}"Output: trueExample 3:
Input: s = "(]"Output: falseExample 4:
Input: s = "([])"Output: trueExample 5:
Input: s = "([)]"Output: falseConstraints:
-
s.length sconsists of parentheses only'()[]{}'.
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”Rule 2 says brackets must close in the reverse order of opening: the bracket opened most recently must be the first one closed. That is last-in, first-out — a stack.
Keep a stack of brackets that are open but not yet closed. An opening bracket is pushed. A closing bracket must match the bracket on top of the stack (rules 1 and 2); if the stack is empty, there is nothing for it to close (rule 3). At the end, anything left on the stack was never closed.
Algorithm
Section titled “Algorithm”- For each character
cofs:- If
cis(,[or{, push it ontost. - Otherwise compute the matching opener
openforc. Ifstis empty orst.top() != open, returnfalse; else pop.
- If
- Return
st.empty().
Walkthrough
Section titled “Walkthrough”Example 5, "([)]":
c | stack before | action |
|---|---|---|
( | empty | push |
[ | ( | push |
) | ( [ | top is [, not ( — return false |
Example 4, "([])", pushes ( and [, then ] pops [ and ) pops (, leaving the stack empty: true.
Complexity
Section titled “Complexity”- Time: — each character is pushed and popped at most once.
- Space: — the stack holds up to
nopeners, e.g. for"((((".
Edge cases
Section titled “Edge cases”- Closing bracket first (
"]"): the stack is empty, so the code returnsfalse. - Unclosed brackets (
"(["): the loop finishes but the stack is not empty, sost.empty()isfalse. - Odd length: always ends with a mismatch or a non-empty stack, so no special case is needed.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class Solution { public: bool isValid(string s) { stack<char> st; for (char c : s) { if (c == '(' || c == '[' || c == '{') { st.push(c); } else { char open = c == ')' ? '(' : c == ']' ? '[' : '{'; if (st.empty() || st.top() != open) return false; st.pop(); } } return st.empty(); }};class Solution { public boolean isValid(String s) { ArrayDeque<Character> st = new ArrayDeque<>(); for (char c : s.toCharArray()) { if (c == '(' || c == '[' || c == '{') { st.push(c); } else { char open = c == ')' ? '(' : c == ']' ? '[' : '{'; if (st.isEmpty() || st.pop() != open) return false; } } return st.isEmpty(); }}class Solution: def isValid(self, s: str) -> bool: match = {')': '(', ']': '[', '}': '{'} stack = [] for c in s: if c in '([{': stack.append(c) elif not stack or stack.pop() != match[c]: return False return not stackGive it a try first
Attempt the problem on LeetCode — the code will still be here.