← Data Structures
5 / 25
Lesson 5 — Stacks: balanced brackets
Stack in action: balanced brackets
Are the brackets in "(a[b]{c})" balanced? A stack answers it. Walk through the text: on an opening bracket, push it. On a closing bracket, the top of the stack must be its matching opener — pop it and compare. At the end the stack must be empty.
pairs = {")": "(", "]": "[", "}": "{"}
pairs[")"] # "(" — the opener that ")" needs
Why it matters: code editors, compilers and JSON parsers check nesting exactly this way.
Want it another way?
Task
Fill in the two TODOs: push openers, and for closers return False if the stack is empty or its popped top is not the matching opener.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
Test your knowledge
A quick 3-question quiz on this lesson — instant feedback.