Skip to content
LeetQuant
QD01 Data Structures and Algorithms

QD01 · Data Structures and Algorithms · Lesson 4 of 7

Linked Lists, Stacks and Queues

When a linked list, stack, queue or deque is the right structure, reversing a list, Floyd's cycle detection with proof, monotonic stacks for next-greater questions, and a time-based rolling maximum.

17 min

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 O(n2)O(n^2) into O(n)O(n).

Which structure, when

StructureFast operationsTypical use
Dynamic array (list)index, push/pop at the endalmost everything; best cache behaviour
Doubly linked listinsert or unlink given a node, O(1)O(1)the orders at one price level, LRU caches
Stack (LIFO)push, pop, peek at the topundo, bracket matching, DFS, expression parsing, monotonic stacks
Queue (FIFO)push at the back, pop at the frontBFS, task queues, time priority at a price
Dequepush and pop at both endssliding windows, monotonic deques

The linked list's selling point is O(1)O(1) 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 O(n)O(n) 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. O(n)O(n) time, O(1)O(1) 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 O(1)O(1) amortised, a common follow-up question.

Floyd's cycle detection

Many problems hide a sequence xt+1=f(xt)x_{t+1} = f(x_t) on a finite set: a linked list's next pointers, a pseudo-random generator, "find the duplicate in an array of n+1n + 1 values from 1..n1..n". Any such sequence eventually repeats, so it looks like the letter rho: a tail of length μ\mu leading into a cycle of length λ\lambda. Floyd's algorithm finds both with O(1)O(1) memory, where a set of visited values would need O(μ+λ)O(\mu + \lambda).

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 λ\lambda further steps.

Phase 2: why restarting from the head finds the cycle start. Suppose they meet after the tortoise has taken ss steps, landing aa steps into the cycle, so s=μ+as = \mu + a. The hare took 2s2s steps and is at the same point, so it has done whole extra laps: 2s−s=s=kλ2s - s = s = k\lambda for some integer kk. Hence μ+a=kλ\mu + a = k\lambda, i.e. μ≡−a(modλ)\mu \equiv -a \pmod{\lambda}: walking μ\mu more steps from the meeting point lands exactly on the cycle start. So put one pointer back at x0x_0, step both one at a time, and they meet at the start after exactly μ\mu steps.

Phase 3. From the start, walk one pointer around until it returns: that is λ\lambda.

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 x0=3x_0 = 3, xt+1=(xt2+1) mod 255x_{t+1} = (x_t^2 + 1) \bmod 255.

Show solution

32+1=103^2 + 1 = 10; 102+1=10110^2 + 1 = 101; 1012+1=10,202=40×255+2101^2 + 1 = 10{,}202 = 40 \times 255 + 2, so 22; then 55, 2626; 262+1=677=2×255+16726^2 + 1 = 677 = 2 \times 255 + 167, so 167167; 1672+1=27,890=109×255+95167^2 + 1 = 27{,}890 = 109 \times 255 + 95, so 9595; 952+1=9,026=35×255+10195^2 + 1 = 9{,}026 = 35 \times 255 + 101, so 101101 again.

The sequence is 3,10,101,2,5,26,167,95‾,101,…3, 10, \underline{101, 2, 5, 26, 167, 95}, 101, \dots. Two values (3 and 10) precede the cycle, so μ=2\mu = 2, and the cycle 101→2→5→26→167→95101 \to 2 \to 5 \to 26 \to 167 \to 95 has λ=6\lambda = 6 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 O(n2)O(n^2) 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 O(n)O(n). 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 ww 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 t=7t = 7 the window is (2,7](2, 7], so 12.0 (at t=1t = 1) and 11.0 (at t=2t = 2) 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: O(n)O(n) total, against O(n⋅ticks per window)O(n \cdot \text{ticks per window}) 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 solution

Write the stack as prices (it really holds indices).

  • Day 0 (100): push. Stack [100][100].
  • Day 1 (98): no pop. Stack [100,98][100, 98].
  • Day 2 (99): pops 98 (day 1, wait 2−1=12 - 1 = 1). Stack [100,99][100, 99].
  • Day 3 (97): push. Stack [100,99,97][100, 99, 97].
  • Day 4 (101): pops 97 (day 3, wait 1), 99 (day 2, wait 2), 100 (day 0, wait 4). Stack [101][101].
  • Day 5 (100): push. Stack [101,100][101, 100].
  • Day 6 (102): pops 100 (day 5, wait 1) and 101 (day 4, wait 2). Stack [102][102].

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 O(1)O(1) 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 O(1)O(1) memory; the meeting point satisfies μ+a=kλ\mu + a = k\lambda, 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 O(n)O(n); a monotonic deque gives rolling maxima over count or time windows in O(n)O(n).
  • 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).