Um momento
0x60Lesson 7 of 13

Match and order with stacks and queues

Use LIFO and FIFO structures for nesting, undo, and level-by-level work.

20 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Choose between a stack and a queue.
  • Validate nested brackets with a stack.
  • Use a deque for efficient queue operations.

A stack is last-in, first-out (LIFO): push and pop at the same end. It fits anything nested or reversible - matching brackets, undo history, evaluating expressions, depth-first search. A queue is first-in, first-out (FIFO): add at the back, remove at the front. It fits processing in arrival order and breadth-first search.

Stacks and queues in Python

  • Stack: a plain list - append() pushes and pop() pops, both O(1).
  • Queue: collections.deque - append() adds and popleft() removes, both O(1). Avoid list.pop(0), which is O(n).
  • Monotonic stack: a stack kept in increasing or decreasing order finds the “next greater element” for every item in O(n) total.
solution.py
1def is_balanced(text):
2    pairs = {")": "(", "]": "[", "}": "{"}
3    stack = []
4    for char in text:
5        if char in "([{":
6            stack.append(char)
7        elif char in pairs:
8            if not stack or stack.pop() != pairs[char]:
9                return False
10    return not stack
11
12print(is_balanced("{[()()]}"), is_balanced("([)]"), is_balanced("(("))
Output
True False False

Every opening bracket waits on the stack for its partner; the most recent unmatched opener must close first, which is exactly LIFO order. Two edge cases catch many candidates: a closing bracket when the stack is empty, and openers left on the stack at the end.

Key takeaways

  • Stacks are LIFO: nesting, undo, DFS, monotonic-stack problems.

  • Queues are FIFO: arrival order, BFS.

  • Use deque for queues in Python.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: solve interview problems

Solve a classic interview problem in Python and run it against test cases. Aim for the optimal complexity, then check the edge cases. Exercises run locally in your browser.

Exercise 1

Validate brackets

+25 XP

Read a string made of the characters ()[]{}. Print valid if every bracket is closed by the same type in the correct order, otherwise invalid.

  • Nested
  • Crossed
  • Unclosed
  • Starts with a closer
main.py
Loading editor…

Python runs in a sandboxed browser worker with a 60 second time limit. Its runtime loads from the Pyodide CDN; your code stays in this browser.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: