Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Balanced Brackets

Medium · 55 XP

Write is_balanced(s) returning True when every bracket ()[]{} is closed in the right order. Print the result for four test strings.

Target output
{[()]} True
{[(])} False
((())) True
(] False
Blank · autosaved
PYbalanced-brackets.py
Run your code to check it…
Guide

How to approach Balanced Brackets

Brackets must close in the reverse order they opened, which is exactly what a stack gives you: last in, first out. Push every opening bracket. On a closing bracket, pop the most recent opener and check that it is the matching partner.

A dictionary from each closer to its opener (")": "(" and so on) makes the check a single lookup. Two more rules finish it: a closer that arrives with an empty stack is unbalanced, and anything left on the stack at the end is unbalanced too.

Worked through on this data

  1. "{[()]}": push {, [, (. Then ) pops (, ] pops [, } pops {. The stack ends empty: True.
  2. "{[(])}": push {, [, (. Then ] pops ( , which is not its partner: False immediately.
  3. "(]": push (, then ] pops ( and fails: False. "((()))" balances: True.

Common mistakes

  • Just counting openers and closers: "{[(])}" has equal counts of every type and still is not balanced.
  • Calling stack.pop() on an empty list raises an IndexError on input such as ")(". Check if not stack first.
  • Returning True when the loop ends without checking the stack, so "((" passes.

Time and space

One pass with constant work per character: O(n) time, and O(n) space in the worst case when every character is an opener.

Where this shows up

Every code editor that highlights a mismatched bracket, and every parser for JSON, HTML or Python itself, runs a stack like this one.

Take it further

Return the index of the first character that breaks the balance instead of False, so an editor could underline it.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path