Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Stacks and queues
EXPERIMENT 12 / 66

Every opening needs the right ending.

Use nesting order rather than counting opening and closing symbols.

BY NAVAN SAMI◷ 8 MIN READSTARTERALGORITHM

01 Model the idea

Balanced bracket matching is about order and type, not merely equal counts. The most recently opened bracket must be the next one closed, which is exactly a stack’s rule. Ignore ordinary characters, push opening brackets, and match closing brackets against the stack top. A completed scan is valid only if no opening remains.

THE THING THAT MUST STAY TRUE

The stack contains exactly the unmatched openings in nesting order.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
PUSH every opening
FOR each closing: match and pop the latest opening
REQUIRE an empty stack at the end

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

balanced_brackets.py
def balanced(text):
    pairs = {')': '(', ']': '[', '}': '{'}
    stack = []
    for character in text:
        if character in pairs.values(): stack.append(character)
        elif character in pairs:
            if not stack or stack.pop() != pairs[character]: return False
    return not stack
print(balanced("{a:[(b)]}"))
print(balanced("([)]"))
↳ EXPECTED OUTPUT
True
False
  1. 1

    The stack stores unresolved openings in nesting order. A closing character must correspond to its most recent entry.

  2. 2

    A closing bracket with an empty stack is an immediate failure. Leftover openings at the end are also a failure.

  3. 3

    This is a bracket exercise, not a complete programming-language parser. Quoted strings, comments, and escape sequences would require lexical analysis before deciding which characters count as syntax.

04 Count the cost

TIME

O(n)

SPACE

O(n) worst-case stack

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Test empty text, an unmatched closing bracket, and unfinished opening brackets.

Reveal one possible solution +
one_possible_solution.py
def balanced(text):
    pairs, stack = {')':'(', ']':'[', '}':'{'}, []
    for ch in text:
        if ch in '([{': stack.append(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]: return False
    return not stack
assert balanced("")
assert not balanced(")")
assert not balanced("((")
print("Nesting checks passed")

06 Check your reasoning

QUICK SIGNAL CHECK

Why use a stack?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.