Do the brackets in a line balance?

Stacks and queues Junior Python 3.13+ Kotlin 2.4+ Reviewed By Best Latest Apps

Predict the output

What does this print?

Python 3.13
line = "{a[b(c)d]e}("
opened = []
for ch in line:
    if ch in "([{":
        opened.append(ch)
    elif ch in ")]}":
        opened.pop()
print(opened)

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A ['(']

Right: everything pairs off except the last open bracket.

A non-empty stack at the end means something was left open, so this line does not balance.

Why not the others?
  • B []. The final '(' is never closed.
  • C ['{', '(']. The '{' is closed by the '}' before the last '('.

30-second answer

Push each opening bracket onto a stack. On a closing bracket, the top of the stack must be its partner; pop it, or fail if the stack is empty or holds the wrong kind. At the end the stack must be empty. O(n) time, O(n) space in the worst case.

Practise saying it · 30 s. No recording, just a timer

Explain the bracket-matching stack.

Say your answer out loud, then check which of these points you covered:

  • Push openers
  • Closer must match the top
  • Empty at the end

Deep dive

The stack captures nesting: the most recent open bracket is the one that must close first.

A single counter works only when there is one bracket kind.

Other characters are skipped, which is what config or code checkers need.

Python solution Ran on Python 3.13.5 · mypy --strict
Python 3.13
PAIRS = {")": "(", "]": "[", "}": "{"}


def brackets_balance(line: str) -> bool:
    opened: list[str] = []
    for ch in line:
        if ch in "([{":
            opened.append(ch)
        elif ch in PAIRS:
            if not opened or opened.pop() != PAIRS[ch]:
                return False
    return not opened

Kotlin Ran on Kotlin 2.4.21 · JDK 21.0.12.1
Kotlin 2.4
fun bracketsBalance(line: String): Boolean {
    val pairs = mapOf(')' to '(', ']' to '[', '}' to '{')
    val opened = ArrayDeque<Char>()
    for (ch in line) {
        if (ch in "([{") opened.addLast(ch)
        else if (ch in pairs) {
            if (opened.isEmpty() || opened.removeLast() != pairs[ch]) {
                return false
            }
        }
    }
    return opened.isEmpty()
}

Common mistakes

  • Returning True when brackets are left open at the end.
  • Popping from an empty stack on a stray closing bracket.

Senior take & follow-ups

Mention the two failure cases (wrong partner, leftovers) before writing code.

Follow-up questions

Think of your answer first, then open the hint.

  1. How would you report the position of the first error?

    Show hint

    Return the index where a mismatch or stray closer occurs, or the index of the oldest unclosed bracket.

  2. What is the fewest insertions to fix the line?

    Show hint

    Count unmatched closers as you go, plus what remains open at the end.

See it animated on iPhone (Stack in DSA Master - Data & Algorithms)

What each operation costs: Stack · Queue · Deque

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.