datarekha
Coding Patterns Easy Asked at AmazonAsked at GoogleAsked at Meta

Check whether a string of brackets is valid.

The short answer

Use a stack: push every opening bracket and pop when you see a closing bracket, checking that it matches the top. If the stack is empty at the end, the string is valid. This is the canonical stack problem — O(n) time, O(n) space.

How to think about it

Recognise the pattern

Any time you need to match the most-recently-opened thing with the current closing token, think stack. Brackets demand exactly that: the innermost open bracket must be closed first — last in, first out.

Build the approach step by step

Brute force: repeatedly strip matched pairs (), [], {} from the string until nothing changes, then check if it is empty. Correct, but O(n²) and awkward.

Stack approach:

  1. Keep a stack of unmatched opening brackets.
  2. Scan each character:
    • Opening bracket ((, [, {) → push it.
    • Closing bracket (), ], }) → if the stack is empty or the top does not match, return False. Otherwise pop.
  3. After the loop, return True only if the stack is empty (no unclosed openers left).

The matching is captured cleanly in a dict: closing -> opening.

Input:  { [ ( ) ] }
Stack:  { → {[ → {[( → {[ → { → empty  ✓

Complexity

ValueWhy
TimeO(n)Single pass through the string
SpaceO(n)Worst case all openers, e.g. "((((("

Keep practising

All Coding Patterns questions

Explore further

Skip to content