Learn / Stacks and queues

Balanced brackets

Walk the string with a stack of open brackets. A closer must match the opener on top; at the end the stack must be empty. Many follow-ups only need counts: the number of unmatched openers and closers, or a range of possible depths.

How to recognise it

  • The input is a string of brackets, maybe with other characters.
  • The question is whether it is balanced, how long the best balanced part is, or how many changes would fix it.
  • Matching pairs nest inside each other: the latest opener closes first.

The basic check

for each character c:
    if c is an opener: push c
    else if the stack is empty or its top does not match c: not balanced
    else: pop
balanced if the stack is empty at the end

Each closer must close the most recent opener still open, and the top of a stack is exactly that.

When counts are enough

With one bracket type, a stack of identical symbols is just a number. Keep open, the number of unmatched (. A ) either lowers it or, at 0, counts as an unmatched closer. After the scan the leftovers always look like )))...(((, and fixes are worked out from the two counts.

A range of depths

A wildcard such as * could be (, ) or nothing. Instead of trying every choice, keep the lowest and highest depth reachable. If even the highest drops below 0, there are too many closers. Clip the lowest at 0. The string can balance when the lowest ends at 0.

Stacks of indexes

Pushing indexes instead of characters tells you where things are. The longest valid run ending at i is i minus the index under the matched opener.

Common mistakes

  • Popping an empty stack when a closer comes first.
  • Returning true without checking that the stack is empty at the end.
  • Forgetting that an odd-length string can never be balanced.

Problems

0 of 6 solved

Check yourself

Which string is balanced?

When only one kind of bracket appears, what can replace the stack?

After matching what you can in ))((, how many reversals balance it?

For the longest valid substring, what does the stack keep at its bottom?