Valid Parentheses

easyStack48 stepsJava · Python · C++

Check that every bracket is closed by the same type in the right order. Push opening brackets; on a closing bracket the top of the stack must be its partner. The string is valid only if the stack ends empty.

▶ Watch the animated trace

Traced input: s = "{[()]}()" → true. Original problem: neetcode.io/problems/validate-parentheses

Complexity

BestO(1)
AverageO(n)
WorstO(n)
SpaceO(n)

Best case is an immediate mismatch. The stack can hold n/2 brackets.

Key idea

Common mistakes

Solution

Java
boolean isValid(String s) {
    Deque<Character> stack = new ArrayDeque<>();
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c == '(' || c == '[' || c == '{') {
            stack.push(c);
            continue;
        }
        char open = c == ')' ? '(' : c == ']' ? '[' : '{';
        if (stack.isEmpty() || stack.peek() != open) {
            return false;
        }
        stack.pop();
    }
    return stack.isEmpty();
}
Python
def isValid(s: str) -> bool:
    pairs = {')': '(', ']': '[', '}': '{'}
    stack = []
    for c in s:
        if c in '([{':
            stack.append(c)
            continue
        if not stack or stack[-1] != pairs[c]:
            return False
        stack.pop()
    return not stack
C++
bool isValid(string s) {
    stack<char> st;
    for (char c : s) {
        if (c == '(' || c == '[' || c == '{') {
            st.push(c);
            continue;
        }
        char open = c == ')' ? '(' : c == ']' ? '[' : '{';
        if (st.empty() || st.top() != open) {
            return false;
        }
        st.pop();
    }
    return st.empty();
}

Edge cases

Each one has its own trace in the interactive view.

CaseInputAnswer
Wrong order
The ) meets [ on top of the stack.
s = "([)]"false
Only openers
The stack isn't empty at the end.
s = "(("false
Starts with a closer
Nothing to match against.
s = "]"false
Empty string
No brackets, nothing unbalanced.
s = ""true
Simple pairs
Each pair opens and closes immediately.
s = "()[]{}"true
← Capacity To Ship Packages Within D DaysMin Stack →