Objective
Choose between an array, a linked list, a stack, a queue and a deque from the operations a problem needs; write pointer manipulations (reversal, cycle detection) without bugs; and use a monotonic stack or deque to turn "for each element, find the nearest larger one" from into .
Which structure, when
| Structure | Fast operations | Typical use |
|---|---|---|
Dynamic array (list) | index, push/pop at the end | almost everything; best cache behaviour |
| Doubly linked list | insert or unlink given a node, | the orders at one price level, LRU caches |
| Stack (LIFO) | push, pop, peek at the top | undo, bracket matching, DFS, expression parsing, monotonic stacks |
| Queue (FIFO) | push at the back, pop at the front | BFS, task queues, time priority at a price |
| Deque | push and pop at both ends | sliding windows, monotonic deques |
The linked list's selling point is removal when you already hold the node, which is exactly the order-book case: a hash map finds the order, and unlinking it from its level does not shift anything. Its costs are indexing, a pointer per element and poor cache locality, so a linked list chosen only "for fast inserts" usually loses to an array in practice. In Python, a stack is a list, and a queue or deque is collections.deque (never list.pop(0)).
Reversing a linked list
The canonical pointer exercise. Walk the list once, turning each next pointer around, and keep the node you came from:
class Node:
def __init__(self, val, next=None):
self.val, self.next = val, next
def reverse(head):
prev = None
while head:
head.next, prev, head = prev, head, head.next
return prev # the old tail is the new head
def to_list(head):
out = []
while head:
out.append(head.val)
head = head.next
return out
print(to_list(reverse(Node(1, Node(2, Node(3, Node(4))))))) # [4, 3, 2, 1]
The tuple assignment evaluates all three right-hand values first, then assigns left to right, so head.next is set on the current node before head moves on. time, space. Written as three separate lines, the order must be: save nxt = head.next, set head.next = prev, then prev = head and head = nxt. Out loud, check the empty list and a single node.
Stacks: last in, first out
A stack answers "what is the most recent unmatched thing?". Bracket matching is the template: push openers, and each closer must match the top.
def balanced(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for c in s:
if c in "([{":
stack.append(c)
elif c in pairs:
if not stack or stack.pop() != pairs[c]:
return False
return not stack # leftovers are unmatched openers
print(balanced("{[()()]}"), balanced("([)]")) # True False
A queue can be built from two stacks: push onto an inbox; to pop, if the outbox is empty, move the whole inbox across (reversing it), then pop the outbox. Each element is moved at most once, so every operation is amortised, a common follow-up question.
Floyd's cycle detection
Many problems hide a sequence on a finite set: a linked list's next pointers, a pseudo-random generator, "find the duplicate in an array of values from ". Any such sequence eventually repeats, so it looks like the letter rho: a tail of length leading into a cycle of length . Floyd's algorithm finds both with memory, where a set of visited values would need .
Phase 1. Move a tortoise one step and a hare two steps at a time until they meet. Once both are on the cycle, the gap between them shrinks by one each step, so they meet within further steps.
Phase 2: why restarting from the head finds the cycle start. Suppose they meet after the tortoise has taken steps, landing steps into the cycle, so . The hare took steps and is at the same point, so it has done whole extra laps: for some integer . Hence , i.e. : walking more steps from the meeting point lands exactly on the cycle start. So put one pointer back at , step both one at a time, and they meet at the start after exactly steps.
Phase 3. From the start, walk one pointer around until it returns: that is .
def floyd(f, x0):
slow, fast = f(x0), f(f(x0))
while slow != fast: # phase 1: meet inside the cycle
slow, fast = f(slow), f(f(fast))
mu, slow = 0, x0 # phase 2: find the start of the cycle
while slow != fast:
slow, fast = f(slow), f(fast)
mu += 1
lam, fast = 1, f(slow) # phase 3: measure its length
while slow != fast:
fast = f(fast)
lam += 1
return mu, lam
print(floyd(lambda x: (x * x + 1) % 255, 3)) # (2, 6)
Worked example
tracing the rho
Check the output (2, 6) above by listing the sequence , .
Show solutionHide solution
; ; , so ; then , ; , so ; , so ; , so again.
The sequence is . Two values (3 and 10) precede the cycle, so , and the cycle has elements. The same code applied to f = lambda i: a[i] on a = [3, 1, 3, 4, 2] finds the duplicated value 3 as the cycle start: two indices point at it, so it is where the tail joins the cycle.
Monotonic stacks: the next greater element
"For each day, how many days until a higher price?" is if you scan forward from every day. Instead keep a stack of days still waiting for a higher price. Their prices are non-increasing from bottom to top (a day sitting above a lower one would already have answered it). When a new price arrives, it answers every waiting day with a lower price, and those are all on top:
def days_to_higher(prices):
wait = [0] * len(prices) # 0 = never sees a higher price
stack = [] # indices still waiting; prices non-increasing
for i, p in enumerate(prices):
while stack and prices[stack[-1]] < p:
j = stack.pop()
wait[j] = i - j
stack.append(i)
return wait
print(days_to_higher([100, 98, 99, 97, 101, 100, 102])) # [4, 1, 2, 1, 2, 1, 0]
Each index is pushed once and popped at most once, so the scan is . Variants: "previous smaller element" (scan the other way or flip the comparison), the largest rectangle in a histogram, and stock-span questions. Decide up front whether ties should pop (< versus <=) and say why.
Monotonic deques: a rolling maximum over a time window
A fixed window of elements is handled by a deque of indices with decreasing values. Market data usually asks for a window in time ("highest trade in the last 5 seconds") with irregular ticks, and the same idea works: store (time, price) pairs, pop from the back anything the new price dominates, and pop from the front anything too old.
from collections import deque
def rolling_max(ticks, horizon):
"""ticks: (time, price) in time order. Max price over (t - horizon, t] at each tick."""
dq, out = deque(), [] # prices strictly decreasing front to back
for t, p in ticks:
while dq and dq[-1][1] <= p: # dominated: older and no higher
dq.pop()
dq.append((t, p))
while dq[0][0] <= t - horizon: # expired from the front
dq.popleft()
out.append(dq[0][1])
return out
ticks = [(0, 10.0), (1, 12.0), (2, 11.0), (4, 10.5), (7, 10.2), (8, 9.9)]
print(rolling_max(ticks, 5)) # [10.0, 12.0, 12.0, 12.0, 10.5, 10.5]
At the window is , so 12.0 (at ) and 11.0 (at ) have expired and 10.5 is the maximum. The front of the deque never empties, because the tick just pushed is always inside its own window. Again each tick is pushed and popped once: total, against for rescanning.
Worked example
tracing the monotonic stack
Trace days_to_higher on [100, 98, 99, 97, 101, 100, 102] and confirm [4, 1, 2, 1, 2, 1, 0].
Show solutionHide solution
Write the stack as prices (it really holds indices).
- Day 0 (100): push. Stack .
- Day 1 (98): no pop. Stack .
- Day 2 (99): pops 98 (day 1, wait ). Stack .
- Day 3 (97): push. Stack .
- Day 4 (101): pops 97 (day 3, wait 1), 99 (day 2, wait 2), 100 (day 0, wait 4). Stack .
- Day 5 (100): push. Stack .
- Day 6 (102): pops 100 (day 5, wait 1) and 101 (day 4, wait 2). Stack .
Day 6 is never popped, so its wait stays 0. Seven pushes and six pops: linear work, as claimed.
Knowledge check
In Floyd's algorithm the tortoise and hare first meet after the tortoise has taken s steps. Which statement is always true?
Knowledge check
A queue is implemented with two stacks (push to an inbox; pop from an outbox, refilling it from the inbox only when it is empty). What is the cost of n operations?
Knowledge check
Using the next-greater-element stack, what are the waits for prices [5, 4, 3, 6]?
Key takeaways
- Pick the structure from its operations: arrays by default, a doubly linked list for unlink given a node, a stack for most-recent-first, a deque for both ends.
- Reverse a list with three pointers in one pass; check the empty and one-node cases aloud.
- Floyd finds a cycle in memory; the meeting point satisfies , so restarting one pointer at the head meets the other at the cycle start.
- A monotonic stack answers next-greater and previous-smaller questions in ; a monotonic deque gives rolling maxima over count or time windows in .
- Justify linear time by counting pushes and pops: each element enters and leaves once.
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).