Topics / 🏛️ Architecture & Design Patterns / 🧩 Level 31: Data Structures & Design Patterns

Python exercise · about 5 minutes · free

Stack: Balanced Brackets

Undo buttons, parsers and the call stack all run on one idea: last in, first out.

A stack adds and removes from the same end. In Python a list does it: append() to push, pop() to pop. For each closing bracket, the most recent opener must match.

reading "(a[b]{c})": push ( and [: (, [. ] matches the top [ → pop: (. push {: (, {. } and ) pop their partners: empty ✓. balanced if every closer matches the top, and the stack ends emptyreading "(a[b]{c})": push ( and [([] matches the top [ → pop(push {({} and ) pop their partnersempty ✓balanced if every closer matches the top, and the stack ends empty
🌍 Real-life storyReal-life story: compilers, JSON parsers and SQL engines use stacks to check that every opening bracket has a matching close. It is also a top-5 interview question.
Your quest: Write is_balanced(s) returning True if every ( [ { is closed correctly and in order.
Starter code
def is_balanced(s):
    pass

Try it in your browser → Free. Sign in with Google to run it. Your code runs on your device.

In this level you'll learn:
More in Level 31: Data Structures & Design Patterns

Share on LinkedIn