InterviewPrepKit

Home / Coding / Stack

Valid Parentheses

easy Original β†—
Solving tips
  • Recognize the nesting property: the only closer that can legally appear matches the most recently opened bracket, which is exactly a stack's top.
  • Scan once: push openers, and on a closer pop and compare types, failing if the stack is empty or the popped opener doesn't match.
  • Two must-do checks: guard against popping an empty stack (input like ']'), and return not stack at the end so unclosed openers like '((' fail.
  • Counting opens vs closes is not enough (it accepts '([)]'); comparing types via the stack is what rejects interleaving. Target O(n) time and O(n) space.

Problem

You get a string made up only of the six bracket characters: (, ), {, }, [, ]. Decide whether the string is balanced: every opening bracket must be closed by a closing bracket of the same type, and brackets must close in the reverse order they were opened (the most recently opened bracket is always the first one closed). An empty stack of unfinished brackets at the end means the string is valid.

Return True if the string is balanced, False otherwise.

Examples

  • "()[]{}" β†’ True β€” three independent pairs, each opened and immediately closed.
  • "([{}])" β†’ True β€” pairs nest properly: the innermost {} closes first, then [], then ().
  • "(]" β†’ False β€” the closer ] does not match the most recent opener (.
  • "((" β†’ False β€” two openers are never closed.

Constraints

  • 1 <= s.length <= 10^4
  • s consists only of the characters ()[]{}

The length bound means a repeated-rescanning solution (O(n^2)) is already shaky; the expected solution is a single O(n) pass.

Think about it first

Hint 1 Think about what makes `"(]"` invalid: when you reach a closing bracket, only one specific opener is allowed to be "waiting" for it. Which one?
Hint 2 The bracket that was opened most recently must be the first one to close. "Most recent thing first" is exactly what a LIFO structure β€” a stack β€” gives you in O(1).
Hint 3 Scan left to right. Push every opener. On a closer, pop the stack and check that the popped opener is the matching type (fail if the stack is empty or the types differ). The string is valid iff you never fail and the stack is empty at the end.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.