Standard Library
Stack & Queue
Complete lesson for Stack & Queue using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Stack & Queue
Section: Standard Library. Implement stacks and queues in Python with list, deque, and queue — LIFO, FIFO, and priority patterns for interviews.
Stack vs queue ideas
- Stack is LIFO: last in, first out — think undo history or browser back stack.
- Queue is FIFO: first in, first out — think printer jobs or ticket lines.
- Python has no separate stack type; you use
listordequewith disciplined ends. - For multithreaded producers/consumers, use
queue.Queueinstead of bare deque.
| Structure | Remove from | Everyday analogy |
|---|---|---|
| Stack (LIFO) | Same end you insert | Plate stack / Undo |
| Queue (FIFO) | Opposite end | Ticket line |
| Deque | Either end | Double-ended waiting line |
| Priority queue | Highest priority | ER triage |
list as a stack
appendpushes;pop()pops the last element — both amortized O(1) at the end.- Never use
pop(0)orinsert(0, x)for queue behaviour on large lists — they are O(n). - Peek with
stack[-1]after checking the list is non-empty. - Empty check:
if not stack:.
stack = []
stack.append(10)
stack.append(20)
stack.append(30)
print("top", stack[-1])
print("pop", stack.pop())
print("stack", stack) Python stack operations — append, peek, and pop
A stack works only at its top. append pushes an item,
stack[-1] peeks without removing it, and pop() removes the top.
Like a stack of plates, the last plate placed is the first taken —
LIFO: Last In, First Out.
- append(e): push
eon top — the stack grows by one. - stack[-1]: peek the top item (30) without removing it.
- pop(): remove and return the top item (30) — 20 becomes the new top.
- Empty check: use
if not stack:before peek/pop.
deque as a stack
deque.append+deque.popmirrors list-as-stack with O(1) ends.- Prefer deque when you also need left-end operations elsewhere in the same algorithm.
- Clear with
d.clear(); length withlen(d). - Still not thread-safe for complex multi-step critical sections without a lock.
from collections import deque
stack = deque()
stack.append("a")
stack.append("b")
print(stack.pop())
print(stack) deque as a queue
- FIFO recipe:
append(enqueue right) andpopleft(dequeue left). - Alternative:
appendleft+pop— pick one convention and stick to it. - This is the standard BFS queue in Python solutions.
queue.Queueadds blocking and timeouts; deque does not.
from collections import deque
q = deque()
q.append("job-1")
q.append("job-2")
q.append("job-3")
while q:
print("serving", q.popleft()) Python queue operations — append, peek, and popleft
A queue has two ends. With collections.deque, append enqueues at the
rear, q[0] peeks at the front, and
popleft dequeues from the front. Like a ticket line — first joined, first served —
FIFO: First In, First Out.
deque) — join at the rear with append, leave from the front with popleft - append(e): enqueue at the rear.
- q[0]: peek the front item (10) without removing it.
- popleft(): dequeue the front item (10) — 20 becomes the new front.
- Avoid:
list.pop(0)for queues — usedeque.popleftfor O(1).
queue.Queue for threads
import queuethenqueue.Queue(maxsize=0)for an infinite FIFO.put(item)/get()block when full/empty if maxsize is set / queue empty.task_done()andjoin()coordinate worker pools.- Use this when multiple threads share work — not for single-threaded interview BFS.
import queue
q = queue.Queue()
for name in ["A", "B", "C"]:
q.put(name)
while not q.empty():
print(q.get()) LifoQueue and SimpleQueue
queue.LifoQueueis a thread-safe stack (put/get).queue.SimpleQueueis a simpler unbounded FIFO (Python 3.7+) with fewer features than Queue.- Naming confusion:
queue.Queueis FIFO; stack-like isLifoQueue. - For algorithms in one thread, prefer
collections.dequeover these.
import queue
stack = queue.LifoQueue()
stack.put(1)
stack.put(2)
stack.put(3)
while not stack.empty():
print(stack.get()) PriorityQueue basics
queue.PriorityQueueretrieves smallest priority first (min-heap).- Entries are typically
(priority, item)tuples so comparisons work. - If items are not comparable, add a unique counter:
(priority, count, item). heapqis the single-threaded equivalent used in many interview solutions.
import queue
pq = queue.PriorityQueue()
pq.put((2, "medium"))
pq.put((1, "high"))
pq.put((3, "low"))
while not pq.empty():
pri, label = pq.get()
print(pri, label) Balanced parentheses with a stack
- Push opening brackets; on closing, check top matches.
- If stack empty on close, or leftovers at end — invalid.
- Works for
()[]{}with a mapping of closers to openers. - Classic warm-up in campus interviews.
def balanced(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack[-1] != pairs[ch]:
return False
stack.pop()
return not stack
for expr in ["()[]{}", "(]", "({[]})", "((("]:
print(expr, balanced(expr)) Call stack vs explicit stack
- Every function call uses the interpreter call stack — recursion depth is limited (
sys.getrecursionlimit()). - Deep recursion can be rewritten with an explicit
list/dequestack. - DFS often uses a stack; BFS uses a queue.
- Interview tip: state which end is top when you say “stack of pairs”.
def dfs_iter(graph, start):
stack = [start]
seen = set()
order = []
while stack:
node = stack.pop()
if node in seen:
continue
seen.add(node)
order.append(node)
for nxt in reversed(graph.get(node, [])):
if nxt not in seen:
stack.append(nxt)
return order
g = {"A": ["B", "C"], "B": ["D"], "C": [], "D": []}
print(dfs_iter(g, "A")) When to choose which implementation
- Single-thread stack:
list. - Single-thread queue / BFS / both ends:
deque. - Multi-thread producer/consumer:
queue.Queue/LifoQueue/PriorityQueue. - Priority in algorithms (Dijkstra): usually
heapq, not PriorityQueue.
| Use case | Tool | Notes |
|---|---|---|
| Undo / parentheses | list stack | append/pop |
| BFS | deque | append/popleft |
| Thread pool jobs | queue.Queue | blocking put/get |
| Dijkstra / top-k | heapq | min-heap functions |
Advanced — Stack & Queue
Amortized complexity reminders
- list append/pop at end are amortized O(1); insert/pop at index 0 are O(n).
- deque append/pop at either end are O(1); indexing middle is O(n).
- PriorityQueue / heapq push and pop are O(log n).
- Pick the structure whose hot operations match your bottleneck.
Monotonic stack pattern
- Maintain stack of indices whose values are increasing or decreasing.
- Used for next greater element, largest rectangle in histogram, daily temperatures.
- While stack not empty and condition breaks, pop and record answers.
- Always store indices when you need distances, not only values.
def next_greater(nums):
n = len(nums)
ans = [-1] * n
stack = [] # indices, values descending from bottom
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
j = stack.pop()
ans[j] = x
stack.append(i)
return ans
print(next_greater([2, 1, 2, 4, 3])) Monotonic queue / sliding window
- A deque of indices with decreasing values yields window maxima in O(n).
- Drop indices outside the window from the left; drop smaller candidates from the right.
- Same idea works for window minima with the inequality flipped.
- This beats the naive O(nk) scan for large streams.
PriorityQueue tie-breaking
- If two tasks share a priority and the payloads are incomparable, heap compare fails.
- Store
(priority, seq, item)with a monotonicseqcounter. heapqneeds the same pattern for complex items.- Remember PriorityQueue is synchronized — slower than heapq in single-thread code.
import itertools
import queue
pq = queue.PriorityQueue()
seq = itertools.count()
pq.put((1, next(seq), {"task": "write"}))
pq.put((1, next(seq), {"task": "review"}))
pq.put((0, next(seq), {"task": "fix"}))
while not pq.empty():
pri, _, payload = pq.get()
print(pri, payload["task"]) queue sentinel and join patterns
- Workers often stop on a sentinel object (e.g.
None) placed once per worker. Queue.join()waits until as manytask_done()calls as successfulgetwork units.- Forgetting
task_donedeadlocksjoin. - In tutorials without threads, stick to deque demos.
Two-stack queue and two-queue stack
- Classic puzzle: implement queue with two stacks (amortized O(1) with lazy transfer).
- Implement stack with two queues (less practical — know the idea).
- In Python interviews, implementing with deque is usually enough unless they forbid it.
- Explain amortized cost when transferring from in-stack to out-stack.
class QueueFromStacks:
def __init__(self):
self.inn = []
self.out = []
def enqueue(self, x):
self.inn.append(x)
def dequeue(self):
if not self.out:
while self.inn:
self.out.append(self.inn.pop())
if not self.out:
raise IndexError("empty queue")
return self.out.pop()
q = QueueFromStacks()
for v in [1, 2, 3]:
q.enqueue(v)
print(q.dequeue(), q.dequeue(), q.dequeue()) BFS layers and parent pointers
- Store
(node, dist)or keep aparentdict to reconstruct paths. - Mark seen when enqueueing (not when dequeuing) to avoid duplicate queue entries.
- Grid BFS uses the same queue with 4 or 8 directions.
- 0-1 BFS uses deque: push front for weight 0, back for weight 1.
from collections import deque
def shortest(grid, start, goal):
rows, cols = len(grid), len(grid[0])
q = deque([(start[0], start[1], 0)])
seen = {start}
while q:
r, c, d = q.popleft()
if (r, c) == goal:
return d
for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 0 and (nr, nc) not in seen:
seen.add((nr, nc))
q.append((nr, nc, d + 1))
return -1
maze = [
[0, 0, 1, 0],
[1, 0, 0, 0],
[0, 0, 1, 0],
]
print(shortest(maze, (0, 0), (2, 3))) Expression evaluation stacks
- Infix to postfix (Shunting-yard) uses an operator stack.
- Postfix evaluation uses an operand stack.
- Unary minus and precedence tables are common follow-ups.
- Keep operators and numbers in separate conceptual stacks even if one list holds tagged pairs.
Tricky Interview Points
Q1) What is a stack?
Answer A LIFO structure: push and pop from the same end. Used for undo, DFS, parsing, and recursion simulation.
Q2) What is a queue?
Answer A FIFO structure: enqueue at one end, dequeue from the other. Used for BFS, scheduling, and buffering.
Q3) How do you implement a stack in Python?
Answer Use a list with append/pop, or collections.deque with append/pop.
Q4) How do you implement a queue in Python?
Answer Prefer collections.deque with append and popleft. Avoid list.pop(0).
Q5) Why is list a bad queue for large data?
Answer Removing from index 0 shifts all elements — O(n) per dequeue.
Q6) deque vs queue.Queue?
Answer deque is for single-threaded algorithms. queue.Queue is thread-safe with blocking put/get.
Q7) What is LifoQueue?
Answer A thread-safe stack in the queue module (LIFO).
Q8) What is PriorityQueue order?
Answer It is a min-heap: lowest priority number comes out first.
Q9) How do you check balanced parentheses?
Answer Scan with a stack of opening brackets; match each closer to the top.
Q10) DFS vs BFS structure?
Answer DFS uses a stack (or recursion). BFS uses a queue.
Q11) What is a monotonic stack?
Answer A stack kept in sorted order of values to answer next-greater / next-smaller queries in O(n).
Q12) How to avoid PriorityQueue compare errors?
Answer Push (priority, unique_id, item) so ties do not compare payloads.
Q13) What does Queue.join do?
Answer Blocks until each get work item has been matched with task_done.
Q14) Can recursion replace an explicit stack?
Answer Yes for DFS-shaped problems, but depth limits and clarity may favor an explicit stack.
Q15) 0-1 BFS uses which structure?
Answer A deque: pushleft for zero-cost edges, append for cost-one edges.
Simple Programs
List stack undo demo
actions = []
redo = []
for cmd in ["type A", "type B", "type C"]:
actions.append(cmd)
print("do", cmd)
print("undo", actions.pop())
redo.append("type C")
print("current", actions)
print("redo stack", redo) deque printer queue
from collections import deque
printer = deque()
for job in ["Invoice", "Resume", "Photo"]:
printer.append(job)
print("queued", job)
while printer:
print("print", printer.popleft()) Balanced brackets checker
def is_valid(s):
stack = []
match = {")": "(", "]": "[", "}": "{"}
for ch in s:
if ch in match.values():
stack.append(ch)
elif ch in match:
if not stack or stack[-1] != match[ch]:
return False
stack.pop()
else:
return False
return not stack
tests = ["{[()]}", "{[(])}", "((()))", "(()"]
for t in tests:
print(t, is_valid(t)) BFS levels with deque
from collections import deque
graph = {
1: [2, 3],
2: [4, 5],
3: [6],
4: [],
5: [],
6: [],
}
def levels(start):
q = deque([start])
seen = {start}
depth = 0
while q:
print("level", depth, ":", list(q))
for _ in range(len(q)):
node = q.popleft()
for nxt in graph[node]:
if nxt not in seen:
seen.add(nxt)
q.append(nxt)
depth += 1
levels(1) Next greater element
def next_greater_elements(nums):
ans = [-1] * len(nums)
stack = []
for i, value in enumerate(nums):
while stack and nums[stack[-1]] < value:
ans[stack.pop()] = value
stack.append(i)
return ans
print(next_greater_elements([4, 5, 2, 25, 10])) Priority tasks with heapq
import heapq
tasks = []
heapq.heappush(tasks, (2, "email"))
heapq.heappush(tasks, (0, "pager-alert"))
heapq.heappush(tasks, (1, "build"))
while tasks:
pri, name = heapq.heappop(tasks)
print(pri, name) Queue from two stacks
class MyQueue:
def __init__(self):
self.a = []
self.b = []
def push(self, x):
self.a.append(x)
def pop(self):
self._move()
return self.b.pop()
def peek(self):
self._move()
return self.b[-1]
def empty(self):
return not self.a and not self.b
def _move(self):
if not self.b:
while self.a:
self.b.append(self.a.pop())
q = MyQueue()
q.push(10)
q.push(20)
print(q.peek())
print(q.pop())
print(q.pop())
print(q.empty()) Problem Solving Tricks
- Stack with list:
append/pop/ peek[-1]. - Queue with deque:
append/popleft. - Never teach
list.pop(0)as a good queue. - Mark BFS nodes seen at enqueue time to cut duplicates.
- Store indices in monotonic stacks when you need distances.
- Use
(priority, counter, item)in heaps for safe ties. - Prefer
heapqoverPriorityQueuein single-threaded algorithm problems. - Explain LIFO vs FIFO in one sentence before coding.
queue.Queuefor threads;dequefor algorithms.- Recursion depth errors → rewrite with an explicit stack.
Practice Programs List
- Implement push/pop/peek/empty for a stack using list.
- Simulate a helpdesk queue with deque.
- Validate bracket strings including mixed types.
- Run BFS on a dict-of-lists graph and print visit order.
- Solve next greater element with a monotonic stack.
- Use heapq to schedule tasks by priority.
- Build a queue using two stacks and test order.
- Convert a recursive DFS to an iterative stack DFS.
- Find shortest path length in a binary grid with BFS.
- Implement sliding window maximum with a deque.
- Write a min-stack that returns current minimum in O(1).
- Compare timings of list.pop(0) vs deque.popleft for large n.