Part 17 / Topic 6 of 20
Stack and queue (deque)
A stack is last-in, first-out (LIFO): the last thing you added is the first thing you remove. A queue is first-in, first-out (FIFO): whoever joined first is served first. Python's list makes a fine stack (append/pop at the end are O(1)). For a queue, use collections.deque, not a list: deque.append/appendleft/pop/popleft are all O(1), while list.pop(0) and list.insert(0, x) are O(n) because every remaining item has to shift (this is the same lesson Part 14 gives in its speed-ups table).
Think of a stack of plates (take the top one off) versus a queue at a ration shop counter (first in line, first served).
| Operation | list |
collections.deque |
|---|---|---|
| add/remove at the end | O(1) amortised | O(1) |
| add/remove at the front | O(n) (insert(0, x), pop(0)) |
O(1) (appendleft, popleft) |
Flagship real-world example: an undo button, built with a stack. Every action is pushed onto a history stack; undo pops the last one and reverses it.
class TextEditor:
def __init__(self):
self.text = ""
self.history: list[tuple[str, str]] = []
def type(self, text):
self.history.append(("type", text)) # push
self.text += text
def undo(self):
if not self.history:
return
action, value = self.history.pop() # pop: O(1)
if action == "type":
self.text = self.text[: -len(value)]
doc = TextEditor()
doc.type("Dear Asha, ")
doc.type("please ship order 101 ")
doc.undo()
print(doc.text) # 'Dear Asha, '
A FIFO queue, with deque:
from collections import deque
line = deque(["Ravi", "Asha", "Imran", "Kavya"])
served_order = []
while line:
served_order.append(line.popleft()) # first in, first served
print(served_order) # ['Ravi', 'Asha', 'Imran', 'Kavya']
Another classic stack use - checking brackets match - pushes openers and pops to check each closer:
def is_balanced(expression: str) -> bool:
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for char in expression:
if char in "([{":
stack.append(char)
elif char in ")]}":
if not stack or stack.pop() != pairs[char]:
return False
return not stack
print(is_balanced("(a[b]{c})")) # True
print(is_balanced("(a[b)")) # False
A monotonic stack keeps its contents in sorted order by popping everything the new item beats — the trick behind "how long until something bigger comes?" questions. Each index is pushed and popped at most once, so the whole scan is O(n), where comparing every day with every later day would be O(n²):
def days_until_warmer(temps):
waits = [0] * len(temps)
stack = [] # indices of days still waiting
for today, temp in enumerate(temps):
while stack and temps[stack[-1]] < temp:
waiting = stack.pop()
waits[waiting] = today - waiting
stack.append(today)
return waits
print(days_until_warmer([31, 29, 30, 34, 28, 36])) # [3, 1, 1, 2, 1, 0]
⚠️ Using a plain
listas a FIFO queue (list.pop(0)) silently works but gets slower as the queue grows - it is O(n) per removal, not O(1). Swap incollections.dequethe moment something needs "remove from the front."
Practice: valid-brackets / matching-tags checking; an undo-redo stack; a queue simulation (ticket counter, task scheduler, or the BFS queue you will meet in graphs); next-greater-element questions with a monotonic stack.
Practice on LeetCode - start here: Valid Parentheses · Implement Queue using Stacks · Min Stack · Daily Temperatures · Evaluate Reverse Polish Notation
Show the full practice list (17 more problems)
Core practice - gentler first:
| Problem | Difficulty |
|---|---|
| Implement Stack using Queues | Easy |
| Baseball Game | Easy |
| Next Greater Element I | Easy |
| Remove All Adjacent Duplicates In String | Easy |
| Make The String Great | Easy |
| Number of Recent Calls | Easy |
| Design Circular Queue | Medium |
| Validate Stack Sequences | Medium |
| Simplify Path | Medium |
Stretch - tougher; come back once the core feels comfortable:
| Problem | Difficulty |
|---|---|
| Next Greater Element II | Medium |
| Asteroid Collision | Medium |
| Decode String | Medium |
| Online Stock Span | Medium |
| Car Fleet | Medium |
| Remove K Digits | Medium |
| Basic Calculator II | Medium |
| Largest Rectangle in Histogram | Hard |
Full program: examples/06_stack_queue_deque.py.
Exercise 6: Stack/queue — matching log tags
Scenario: A server log wraps related lines in tags, like <request>...</request>, and some logs ship with a missing or mismatched closing tag.
What to do: Write tags_balanced(log: list[str]) -> bool. Each line is either an opening tag ("<name>") or a closing tag ("</name>"). Use a list as a stack: push opening tags; on a closing tag, pop the stack and check its name matches (return False on any mismatch or an empty stack); at the end, the stack must be empty. Print the result for both logs below.
Starting data:
GOOD_LOG = ["<request>", "<db>", "</db>", "</request>"]
BAD_LOG = ["<request>", "<db>", "</request>", "</db>"]
Sample output:
GOOD_LOG balanced: True
BAD_LOG balanced: False
Show the solution to Exercise 6
"""Exercise 6: Stack - matching log tags.
Run: python ex04.py (macOS/Linux: python3 ex04.py)
"""
GOOD_LOG = ["<request>", "<db>", "</db>", "</request>"]
BAD_LOG = ["<request>", "<db>", "</request>", "</db>"]
def tags_balanced(log: list[str]) -> bool:
stack: list[str] = []
for line in log:
name = line.strip("</>")
if line.startswith("</"):
if not stack or stack.pop() != name:
return False
else:
stack.append(name)
return not stack
def main() -> None:
print("GOOD_LOG balanced:", tags_balanced(GOOD_LOG))
print("BAD_LOG balanced:", tags_balanced(BAD_LOG))
if __name__ == "__main__":
main()