Pattern

Valid parentheses

Use a stack to match the most recent unmatched opener when you see a closer.

Stack & Monotonic StackLinear DSPattern

When to use it

Bracket validation, parsing nested structures, removing invalid parentheses variants.

How it works

  1. Push opening brackets.
  2. On a closer, pop and check it matches; fail if stack empty or mismatch.
  3. Succeed only if the stack is empty at the end.

Solution

Reference implementation in C#, Python, Java, JavaScript, and C++.

Exact solutionValid parentheses

Why interviewers care

Teaches the stack discipline used in many later problems (next greater, histogram, calculators).

Drill Valid parentheses with Stack & Monotonic Stack problems — filter the bank and solve 2–3 Easy/Medium items while saying the invariant out loud.

Watch-outs

  • !Returning true with leftovers on the stack
  • !Not handling odd-length leftovers
  • !Mixing bracket types without a pair map
Loading visualization…

Practice this

Related Stack & Monotonic Stack problems — open any one and apply Valid parentheses.

Search bank →

More under Stack & Monotonic Stack

← Back to Stack & Monotonic Stack lesson