Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Stack

Balanced brackets

Easy · Target 10 minutes · Stack· Type asked at

A string s contains only the characters ( ) [ ] { }. Return true if the brackets are balanced: every opening bracket is closed by a bracket of the same type, and brackets close in the reverse order to the one in which they opened. Otherwise return false.

Examples

InputOutputWhy
s = "([]{})"trueEach pair closes inside the pair that contains it.
s = "([)]"falseThe counts match, but ] arrives while ( is still the innermost open bracket.
s = "(("falseTwo brackets are left open at the end.

Constraints

  • 1 ≤ s.length ≤ 10⁴
  • s contains only ( ) [ ] { }

Hints

Hint 1

Counting each type separately is not enough: "([)]" has one of each and is still wrong. What does a closing bracket actually need to match?

Hint 2

A closing bracket must match the most recently opened bracket that has not been closed yet. Which data structure hands you "the most recent" in O(1)?

Hint 3

Push openers. On a closer, the stack must be non-empty and its top must be the matching opener; pop it. At the end the stack must be empty.

Where people lose marks

  • Using one counter per bracket type. It accepts "([)]", where the counts are fine and the nesting is not.
  • Forgetting the empty-stack check on a closing bracket. ")" pops from an empty stack, which crashes in some languages and silently returns undefined in JavaScript.
  • Returning true as soon as the loop ends, without checking that the stack is empty. "((" would pass.
  • Mapping opener to closer and then looking up the wrong direction. Map each closer to the opener it needs; that is the lookup you do.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.