Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Stack

Balanced brackets

Easy · Target 10 minutes · Stack · Type asked atBloombergAmazonGoldman Sachs

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.

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.