Valid Parentheses

EasyStack · Bracket Matching🧩 StackLeetCode #20 ↗Updated

Problem

A string s contains only the bracket characters ( ) [ ] { }. Decide whether it is well-formed: every opening bracket is closed by a bracket of the same type, and brackets close in the reverse order they were opened (properly nested).
Input"([]{})"Outputtrue
Input"(]"Outputfalse
Input"([)]"Outputfalse

1 ≤ s.length ≤ 104  ·  s consists only of ()[]{}

Try it yourself

Java
class Solution {
    public boolean isValid(String s) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The bracket that must close next is always the most recently opened one that is still open — last in, first out, i.e. a stack.
PatternStack

Instinct Things resolve in reverse order of arrival (brackets, adjacent pairs, nested expressions) - push now, pop when its partner shows up.

Memory hack Last in, first out - like a pile of plates, you only ever touch the one on top; every closer pops its opener.

Open the Stack guide →

Approaches

Brute ForceRepeatedly Delete Adjacent Pairs

Time O(n2)Space O(n)

Any valid string contains an innermost pair (), [] or {} side by side. Delete all such pairs and repeat until nothing changes; the string was valid iff it shrinks to empty.

Java
public boolean isValid(String s) {
    String prev;
    do {
        prev = s;
        s = s.replace("()", "").replace("[]", "").replace("{}", "");
    } while (!s.equals(prev));
    return s.isEmpty();
}

Cute and short, but up to n/2 rounds of O(n) string rebuilding.

At a glance

LevelApproachTimeSpace
Brute ForceRepeatedly Delete Adjacent PairsO(n2)O(n)
BetterStack + Closer→Opener MapO(n)O(n)
OptimalArray Stack of Expected ClosersO(n)O(n)
Common pitfalls
  • Only counting brackets — "([)]" has balanced counts but is invalid.
  • Popping an empty stack on a leading closer like ")".
  • Returning true without checking the stack is empty — "((" fails.
Interview tips
  • Explain why LIFO matches nesting: the last opened must be the first closed.
  • Mention the odd-length early exit as a free optimisation.
  • Compare two Character objects with equals, never !=.
Pattern
Stack for nested matching → brackets, tags, or any open/close pairs that must nest.
My notes saved in this browser