TRT
Sign in
easyFoundationsLeetCode#stack#matching pairs

Valid parentheses

Decide whether a string of (), [] and curly brackets is balanced, with each closer matching the most recent unclosed opener.

The Runtime Theory Team1 min read
Taught inStacks and the LIFO ruleA stack only lets you touch its most recent item. That restriction makes it cheap to build on an array, and it is exactly what nested structure, undo and matching brackets need.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

ins = "()[]{}"

outtrue

ins = "(]"

outfalse

ins = "([)]"

outfalse

Given a string containing only the characters ()[]{}, return whether it is valid: every opening bracket is closed by the same type of bracket, and brackets close in the correct order.

Before you code

Counting each type of bracket isn't enough: ([)] has one of each but is invalid. What matters is which opener is the most recent one still open.

Hints

  1. Push each opener onto a stack.
  2. For each closer, the stack must be non-empty and its top must be the matching opener; pop it.
  3. A map from closer to opener keeps the check to one line.
  4. At the end, the stack must be empty: "((" has no mismatch but leaves openers unclosed.

Production & complexity notes

When solving Valid parentheses on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Stacks and the LIFO rule to reinforce the underlying pattern.

What it practices

Using a stack for nested structure, from Stacks and the LIFO rule.

Not started

Sign in to save your learning progress.

Sign in to save