Skip to main content

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.

L1

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 list or deque with disciplined ends.
  • For multithreaded producers/consumers, use queue.Queue instead of bare deque.
StructureRemove fromEveryday analogy
Stack (LIFO)Same end you insertPlate stack / Undo
Queue (FIFO)Opposite endTicket line
DequeEither endDouble-ended waiting line
Priority queueHighest priorityER triage

list as a stack

  • append pushes; pop() pops the last element — both amortized O(1) at the end.
  • Never use pop(0) or insert(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.

Python stack operations in six steps using a glass jar: 1 empty stack; 2 append(10); 3 append(20); 4 append(30); 5 stack[-1] peeks at 30 and it stays; 6 pop() removes 30, leaving 20 and 10. A side card compares append and pop to a stack of plates, and a footer notes O(1) time.
Python stack (list) — follow the jars from empty through three appends, a peek, and a pop
  • append(e): push e on 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.pop mirrors 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 with len(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) and popleft (dequeue left).
  • Alternative: appendleft + pop — pick one convention and stick to it.
  • This is the standard BFS queue in Python solutions.
  • queue.Queue adds 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.

Python queue operations with collections.deque in six steps: 1 empty; 2 append(10); 3 append(20); 4 append(30); 5 q[0] peeks at 10 and it stays; 6 popleft() removes 10 from the front. A ticket-line analogy and O(1) note are included.
Python queue (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 — use deque.popleft for O(1).

queue.Queue for threads

  • import queue then queue.Queue(maxsize=0) for an infinite FIFO.
  • put(item) / get() block when full/empty if maxsize is set / queue empty.
  • task_done() and join() 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.LifoQueue is a thread-safe stack (put / get).
  • queue.SimpleQueue is a simpler unbounded FIFO (Python 3.7+) with fewer features than Queue.
  • Naming confusion: queue.Queue is FIFO; stack-like is LifoQueue.
  • For algorithms in one thread, prefer collections.deque over 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.PriorityQueue retrieves 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).
  • heapq is 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/deque stack.
  • 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 caseToolNotes
Undo / parentheseslist stackappend/pop
BFSdequeappend/popleft
Thread pool jobsqueue.Queueblocking put/get
Dijkstra / top-kheapqmin-heap functions
L2

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 monotonic seq counter.
  • heapq needs 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 many task_done() calls as successful get work units.
  • Forgetting task_done deadlocks join.
  • 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 a parent dict 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.
L3

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.

L4

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())
L5

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 heapq over PriorityQueue in single-threaded algorithm problems.
  • Explain LIFO vs FIFO in one sentence before coding.
  • queue.Queue for threads; deque for algorithms.
  • Recursion depth errors → rewrite with an explicit stack.
L6

Practice Programs List

  1. Implement push/pop/peek/empty for a stack using list.
  2. Simulate a helpdesk queue with deque.
  3. Validate bracket strings including mixed types.
  4. Run BFS on a dict-of-lists graph and print visit order.
  5. Solve next greater element with a monotonic stack.
  6. Use heapq to schedule tasks by priority.
  7. Build a queue using two stacks and test order.
  8. Convert a recursive DFS to an iterative stack DFS.
  9. Find shortest path length in a binary grid with BFS.
  10. Implement sliding window maximum with a deque.
  11. Write a min-stack that returns current minimum in O(1).
  12. Compare timings of list.pop(0) vs deque.popleft for large n.