Linked Lists, Stacks, and Queues Questions
Pointer-based linear structures and the classic problems built on them: singly, doubly and circular linked lists (reversal whole, partial and in groups of k, cycle detection and cycle start with fast/slow pointers, intersection, middle and nth-from-end, merging two or k sorted lists, sorting a list, reordering, palindrome check, rotation, partitioning, duplicate removal, deep copy with random pointers, flattening child lists, sentinel nodes), implementing lists in C, C++ and Rust with attention to pointer handling, ownership and cleanup, array versus linked-list trade-offs including cache locality, stacks, queues and deques (array, linked and circular-buffer implementations, ring-buffer full versus empty, queue from two stacks, min stack, round-robin scheduling), monotonic stacks and queues (next greater element, largest rectangle in a histogram, sliding-window maximum), stack-based expression and bracket evaluation (balanced brackets, Reverse Polish Notation, infix to postfix, calculators), and structure-level builds such as an LRU cache from a hash map plus doubly linked list, undo/redo history, and variants like persistent or unrolled lists. Foundational for coding interviews and for understanding how higher-level structures are built. Concurrent and lock-free queues, memory allocators, general graph traversal, heaps and cache-eviction system design are covered elsewhere.
Compare singly, doubly and circular linked lists. For each, give memory overhead, the cost of insert, delete (given the node) and traversal, and a realistic use. Which would you pick for an LRU cache, an undo history and a round-robin scheduler, and why?
Sample Answer
The short answer
The three kinds differ by how many pointers each node stores and where the last node points.
- Singly linked: each node has one pointer,
next. Cheapest in memory; you can only walk forward. - Doubly linked: each node has
nextandprev. One more pointer per node buys O(1) removal of any node you hold and walking in both directions. - Circular: the last node points back to the first instead of to
None. It can be singly or doubly linked. There is no end, so a walk from any node reaches every node.
My picks: LRU cache (least-recently-used: evicts the entry untouched for longest) = doubly linked list plus a hash map; undo history = doubly linked list with a cursor (a variable that points at the current node and moves along the list); round-robin scheduler = circular singly linked list. The reasons follow from the cost table.
Memory overhead
The overhead is the pointers per node. In C on a 64-bit machine, with an 8-byte payload, the compiler reports:
#include <stdio.h>
#include <stdint.h>
struct singly { int64_t value; struct singly *next; };
struct doubly { int64_t value; struct doubly *prev, *next; };
int main(void) {
printf("pointer size: %zu bytes\n", sizeof(void *));
printf("singly node (8B value): %zu bytes\n", sizeof(struct singly));
printf("doubly node (8B value): %zu bytes\n", sizeof(struct doubly));
printf("1,000,000 nodes extra for doubly: %zu bytes\n",
1000000 * (sizeof(struct doubly) - sizeof(struct singly)));
return 0;
}
Reading the C: struct singly is a record with an 8-byte integer value and a pointer next to another struct singly; struct doubly adds a second pointer. sizeof gives the size in bytes of a type, and %zu is the printf format for that kind of size value. Compiled with gcc -fsanitize=address,undefined node_sizes.c (the flag turns on run-time checks for memory errors and undefined behaviour, and prints nothing extra when the program is clean) and run, it prints:
pointer size: 8 bytes
singly node (8B value): 16 bytes
doubly node (8B value): 24 bytes
1,000,000 nodes extra for doubly: 8000000 bytes
So a doubly linked node is 24 bytes against 16 for a singly linked one, and a circular singly linked node is the same 16 bytes as a plain singly linked one (the circle reuses the last node's next, which would otherwise hold None). Pointer width depends on the platform: it was 8 bytes above and is commonly 4 on a 32-bit microcontroller, which matters for embedded work. Python and Java objects add their own headers on top, so the byte counts are specific to the C structs shown.
Cost table (n nodes)
| Singly | Doubly | Circular singly (keep a pointer to the last node) | Circular doubly | |
|---|---|---|---|---|
| Pointers per node | 1 | 2 | 1 | 2 |
| Insert at head | O(1) | O(1) | O(1) | O(1) |
| Insert at tail | O(1) with a tail pointer, else O(n) | O(1) with a tail pointer | O(1) | O(1) |
| Insert after a node you hold | O(1) | O(1) | O(1) | O(1) |
| Delete a node you hold | O(n): the predecessor must be found by walking | O(1) | O(n), same reason | O(1) |
| Delete the head | O(1) | O(1) | O(1) | O(1) |
| Traverse | O(n), forward only | O(n), either direction | O(n), stop when you return to the start | O(n), either direction |
| Reach a node's predecessor | O(n) | O(1) | O(n) | O(1) |
"Delete a node you hold" is the row that decides most choices. The following program counts the pointer hops (steps along next) instead of timing anything:
class SNode:
def __init__(self, value):
self.value, self.next = value, None
class DNode:
def __init__(self, value):
self.value, self.prev, self.next = value, None, None
# 1. Delete a node you already hold: singly must find its predecessor, doubly does not.
def delete_given_singly(head, target):
hops, cur = 0, head
while cur.next is not target:
cur, hops = cur.next, hops + 1
cur.next = target.next
return hops
def delete_given_doubly(target):
target.prev.next = target.next
if target.next:
target.next.prev = target.prev
return 0
def hop_demo(n=1000, index=700):
s = [SNode(i) for i in range(n)]
d = [DNode(i) for i in range(n)]
for i in range(n - 1):
s[i].next = s[i + 1]
d[i].next, d[i + 1].prev = d[i + 1], d[i]
print(f"n={n}, delete the node at index {index}:")
print(f" singly list pointer hops to find the predecessor: {delete_given_singly(s[0], s[index])}")
print(f" doubly list pointer hops: {delete_given_doubly(d[index])}")
# 2. Round robin on a circular singly linked list. `before` stays one node behind the
# task whose turn it is, so removing a finished task needs no search.
class Task:
def __init__(self, name, units):
self.name, self.left, self.next = name, units, self
def round_robin(tasks):
ring = [Task(n, u) for n, u in tasks]
for a, b in zip(ring, ring[1:] + ring[:1]):
a.next = b
before, order = ring[-1], []
while True:
current = before.next
current.left -= 1
order.append(current.name)
if current.left == 0:
if current is before: # last task finished
break
before.next = current.next # unlink; `before` stays put
else:
before = current
return order
# 3. LRU order: hash map for lookup, doubly linked list for recency (front = most recent).
class LRU:
def __init__(self, capacity):
self.capacity, self.map = capacity, {}
self.front, self.back = DNode(None), DNode(None) # sentinel (placeholder) ends
self.front.next, self.back.prev = self.back, self.front
def _unlink(self, n):
n.prev.next, n.next.prev = n.next, n.prev
def _push_front(self, n):
n.next, n.prev = self.front.next, self.front
self.front.next.prev = n
self.front.next = n
def get(self, key):
if key not in self.map:
return None
node = self.map[key]
self._unlink(node); self._push_front(node) # O(1): both neighbours are known
return node.value[1]
def put(self, key, val):
if key in self.map:
self._unlink(self.map[key])
elif len(self.map) == self.capacity:
oldest = self.back.prev
self._unlink(oldest)
del self.map[oldest.value[0]]
node = DNode((key, val))
self.map[key] = node
self._push_front(node)
def order(self):
out, n = [], self.front.next
while n is not self.back:
out.append(n.value[0]); n = n.next
return out
# 4. Undo history: one node per document state, a cursor that moves both ways.
class History:
def __init__(self, first):
self.cursor = DNode(first)
def edit(self, state):
node = DNode(state)
node.prev, self.cursor.next = self.cursor, node # a new edit discards the redo chain
self.cursor = node
def undo(self):
if self.cursor.prev:
self.cursor = self.cursor.prev
return self.cursor.value
def redo(self):
if self.cursor.next:
self.cursor = self.cursor.next
return self.cursor.value
if __name__ == "__main__":
hop_demo()
print("round robin, quantum 1, tasks A=3 B=1 C=2 units:", " ".join(round_robin([("A", 3), ("B", 1), ("C", 2)])))
cache = LRU(2)
cache.put("a", 1); cache.put("b", 2); cache.get("a"); cache.put("c", 3)
print("LRU capacity 2 after put a, put b, get a, put c: most recent first =", cache.order())
h = History("v1")
h.edit("v2"); h.edit("v3")
print("undo:", h.undo(), "| undo:", h.undo(), "| redo:", h.redo())
h.edit("v2b")
print("after a new edit, redo stays at:", h.redo())
n=1000, delete the node at index 700:
singly list pointer hops to find the predecessor: 699
doubly list pointer hops: 0
round robin, quantum 1, tasks A=3 B=1 C=2 units: A B C A C A
LRU capacity 2 after put a, put b, get a, put c: most recent first = ['c', 'a']
undo: v2 | undo: v1 | redo: v2
after a new edit, redo stays at: v2b
The first two output lines are the delete row: on a 1,000-node list, deleting the node at index 700 costs 699 hops in the singly linked list (to reach its predecessor) and 0 in the doubly linked list.
Walking the pointers
Two pieces of the code are easy to misread. In _unlink, n.prev.next, n.next.prev = n.next, n.prev is a simultaneous assignment: Python first evaluates the right side (n.next and n.prev) into a pair, then assigns the pair to the left side targets one after the other. Written as separate statements it is n.prev.next = n.next followed by n.next.prev = n.prev. In the round robin, before is the node just behind the task whose turn it is, so before.next is the current task.
The program below prints every pointer after each step of two things: the round robin from the code above (tasks A with 3 units, B with 1, C with 2), and an LRU hit, get(b), on the three-node list a, b, c between the front and back sentinels.
class Task:
def __init__(self, name, units):
self.name, self.left, self.next = name, units, self
def ring_state(tasks):
return " ".join(f"{t.name}[left={t.left} next={t.next.name}]" for t in tasks)
tasks = [Task("A", 3), Task("B", 1), Task("C", 2)]
for a, b in zip(tasks, tasks[1:] + tasks[:1]):
a.next = b
before = tasks[-1]
print("round robin, quantum 1 (each turn runs a task for one unit)")
print(f"{'start':<34}before={before.name} {ring_state(tasks)}")
while True:
current = before.next
current.left -= 1
if current.left == 0:
if current is before:
print(f"turn {current.name}: finished, last task")
break
before.next = current.next
action = f"turn {current.name}: finished, before.next = {current.next.name}"
else:
before = current
action = f"turn {current.name}: runs, before = {current.name}"
print(f"{action:<34}before={before.name} {ring_state(tasks)}")
class DNode:
def __init__(self, label):
self.label, self.prev, self.next = label, None, None
front, back = DNode("front"), DNode("back")
a, b, c = DNode("a"), DNode("b"), DNode("c")
chain = [front, a, b, c, back]
for left, right in zip(chain, chain[1:]):
left.next, right.prev = right, left
def lru_state():
return " ".join(f"{n.label}[prev={n.prev.label if n.prev else '-'} next={n.next.label if n.next else '-'}]"
for n in chain)
print()
print("LRU hit: get(b) with order a, b, c (most recent first)")
print(f"{'start':<30}{lru_state()}")
b.prev.next = b.next
print(f"{'a.next = c':<30}{lru_state()}")
b.next.prev = b.prev
print(f"{'c.prev = a':<30}{lru_state()}")
b.next, b.prev = front.next, front
print(f"{'b.next = a, b.prev = front':<30}{lru_state()}")
front.next.prev = b
print(f"{'a.prev = b':<30}{lru_state()}")
front.next = b
print(f"{'front.next = b':<30}{lru_state()}")
Run, it prints:
round robin, quantum 1 (each turn runs a task for one unit)
start before=C A[left=3 next=B] B[left=1 next=C] C[left=2 next=A]
turn A: runs, before = A before=A A[left=2 next=B] B[left=1 next=C] C[left=2 next=A]
turn B: finished, before.next = C before=A A[left=2 next=C] B[left=0 next=C] C[left=2 next=A]
turn C: runs, before = C before=C A[left=2 next=C] B[left=0 next=C] C[left=1 next=A]
turn A: runs, before = A before=A A[left=1 next=C] B[left=0 next=C] C[left=1 next=A]
turn C: finished, before.next = A before=A A[left=1 next=A] B[left=0 next=C] C[left=0 next=A]
turn A: finished, last task
LRU hit: get(b) with order a, b, c (most recent first)
start front[prev=- next=a] a[prev=front next=b] b[prev=a next=c] c[prev=b next=back] back[prev=c next=-]
a.next = c front[prev=- next=a] a[prev=front next=c] b[prev=a next=c] c[prev=b next=back] back[prev=c next=-]
c.prev = a front[prev=- next=a] a[prev=front next=c] b[prev=a next=c] c[prev=a next=back] back[prev=c next=-]
b.next = a, b.prev = front front[prev=- next=a] a[prev=front next=c] b[prev=front next=a] c[prev=a next=back] back[prev=c next=-]
a.prev = b front[prev=- next=a] a[prev=b next=c] b[prev=front next=a] c[prev=a next=back] back[prev=c next=-]
front.next = b front[prev=- next=b] a[prev=b next=c] b[prev=front next=a] c[prev=a next=back] back[prev=c next=-]
In the round robin, when B finishes, before is A, so the single assignment A.next = C removes B from the ring; B keeps its own stale next but nothing leads to it. When C finishes, before is A again and A.next = A closes the ring around the one remaining task; its last turn takes the "last task" exit. In the LRU hit, the first two steps cut b out (a.next = c, c.prev = a), the third gives b its new neighbours, and a.prev = b must run before front.next = b, because once front.next is b the expression front.next.prev would no longer name a. The order is b, a, c afterwards.
Realistic uses
| Kind | Where it fits |
|---|---|
| Singly | A stack or a queue built from nodes; the collision chains in a hash table (the small list of entries that share one slot); adjacency lists (for each vertex of a graph, the list of its neighbours); any structure only ever walked forward and only changed at the front |
| Doubly | Browser back/forward history; an editor's undo/redo; an LRU cache's recency order; any list where you remove items from the middle by reference |
| Circular | Round-robin scheduling; a repeating playlist; turn order in a game; a ring where "next after the last" must be the first |
Choosing for the three cases
LRU cache: doubly linked list plus hash map. The cache needs two O(1) moves: look up an entry by key (hash map) and move that entry to the front of the recency order (list). Moving a node means unlinking it from the middle, which needs its predecessor. The doubly linked list gives that in O(1); a singly linked list would force a walk and make every cache hit O(n). The output above shows the result: after put a, put b, get a, put c with capacity 2, key b (the least recently used) was evicted and the order is ['c', 'a'].
Undo history: doubly linked list with a cursor. Each node is a document state. Undo moves the cursor to prev, redo moves it to next, and a new edit after an undo cuts off the nodes ahead of the cursor, which is what the last two output lines show (undo twice from v3 gives v2 then v1, redo gives v2, and after a new edit v2b redo has nowhere to go). Two stacks, or an array with an index, also work and are often simpler for a bounded history; the linked list wins when you need to remove or splice states in the middle.
Round-robin scheduler: circular singly linked list. The scheduler gives each task one time slice (a fixed amount of running time, called the quantum; here quantum 1 means one unit per turn) and moves on, wrapping from the last task to the first. A ring has no end to special-case. Finished tasks must be removed, which needs a predecessor, but a round robin always walks forward, so keeping a pointer one node behind the current task (before in the code) supplies it with no search. That makes a second pointer per node wasted memory. The run above schedules A (3 units), B (1) and C (2) with a quantum of 1 as A B C A C A.
Common mistakes
- Choosing singly linked "because it uses less memory" and then needing deletion by reference everywhere.
- Calling a circular list's traversal complete when it loops forever: the walk must stop on returning to its starting node.
- Claiming a linked list is faster than an array in general. A list wins on O(1) splices at a known position and loses on indexing (O(n)) and on memory locality (data stored next to each other is loaded into the processor's cache together, which makes array scans fast), because every hop in a list follows a pointer to a possibly distant address.
- Forgetting that in a doubly linked delete both neighbours must be patched, and the ends (
prevornextofNone) need a guard or a sentinel (a dummy placeholder node at each end that removes those special cases, as the LRU code uses).
Running the code
gcc -fsanitize=address,undefined -o node_sizes node_sizes.c && ./node_sizes
python list_kinds.py
python pointer_walk.py
Python 3.12 and gcc, standard library only (pointer_walk.py is the pointer walk-through program).
Why do many linked list implementations use a dummy (sentinel) head node? Show an insertion and a deletion at the head written with and without one, and say what trade-offs the sentinel brings.
Sample Answer
The idea in plain words
A sentinel (or dummy) node is a node that holds no real data and sits permanently in front of the first real node (or, in a doubly linked list, between the last and the first). Its only job is to make every real node look the same: each one has a predecessor, so "insert here" and "delete this" use the same pointer update no matter where the node is. Without a sentinel, the head is the one node that nobody points to, so every operation that might touch it needs an if head is None or if head.val == x branch. Those branches are where beginner bugs live.
Insertion and deletion at the head, with and without
PlainList stores head directly. SentinelList stores a dummy node whose next is the first real node. Inserting at the head is one line in both. The difference shows up in delete_value: the plain version needs three branches (empty list, head matches, walk the rest), and the sentinel version is only the walk, because the head match is just "the node after dummy".
The code
import random
import sys
class Node:
__slots__ = ("val", "next") # __slots__ fixes the attribute names up front, so Python skips the per-object dictionary and the node is smaller
def __init__(self, val=None, next=None):
self.val, self.next = val, next
class PlainList:
"""Singly linked list with no sentinel: the head is a special case."""
def __init__(self):
self.head = None
def insert_head(self, val):
self.head = Node(val, self.head) # works for empty and non-empty alike
def delete_head(self):
if self.head is None: # branch 1: empty
raise IndexError("empty")
self.head = self.head.next
def delete_value(self, val):
if self.head is None: # branch 2: empty
return False
if self.head.val == val: # branch 3: the head is special
self.head = self.head.next
return True
prev = self.head
while prev.next and prev.next.val != val:
prev = prev.next
if prev.next is None:
return False
prev.next = prev.next.next
return True
def values(self):
node, out = self.head, []
while node:
out.append(node.val)
node = node.next
return out
class SentinelList:
"""Singly linked list with a dummy node in front: every real node has a predecessor."""
def __init__(self):
self.dummy = Node() # its val is never read
def insert_head(self, val):
self.dummy.next = Node(val, self.dummy.next)
def delete_head(self):
if self.dummy.next is None: # the only branch left: empty
raise IndexError("empty")
self.dummy.next = self.dummy.next.next
def delete_value(self, val):
prev = self.dummy
while prev.next and prev.next.val != val:
prev = prev.next
if prev.next is None:
return False
prev.next = prev.next.next
return True
def values(self):
node, out = self.dummy.next, [] # start AFTER the dummy
while node:
out.append(node.val)
node = node.next
return out
class DNode:
__slots__ = ("val", "prev", "next")
def __init__(self, val=None):
self.val, self.prev, self.next = val, None, None
class RingList:
"""Doubly linked list with ONE sentinel that is both head side and tail side."""
def __init__(self):
self.sentinel = DNode()
self.sentinel.prev = self.sentinel.next = self.sentinel # empty ring points at itself
def insert_after(self, node, val):
new = DNode(val)
new.prev, new.next = node, node.next
node.next.prev = new
node.next = new
return new
def remove(self, node):
node.prev.next = node.next
node.next.prev = node.prev
def push_front(self, val):
return self.insert_after(self.sentinel, val)
def push_back(self, val):
return self.insert_after(self.sentinel.prev, val)
def values(self):
out, node = [], self.sentinel.next
while node is not self.sentinel:
out.append(node.val)
node = node.next
return out
def render_plain(lst):
return " -> ".join(map(str, lst.values() + ["None"]))
def render_sentinel(lst):
return " -> ".join(["dummy"] + list(map(str, lst.values() + ["None"])))
if __name__ == "__main__":
plain, sent = PlainList(), SentinelList()
steps = [("insert_head", 3), ("insert_head", 2), ("insert_head", 1),
("delete_value", 1), ("delete_value", 3), ("delete_head", None),
("delete_value", 9)]
for name, arg in steps:
results = []
for lst in (plain, sent):
fn = getattr(lst, name)
results.append(fn(arg) if arg is not None else fn())
label = f"{name}({'' if arg is None else arg})"
print(f"{label:<16}plain: {render_plain(plain):<20} sentinel: {render_sentinel(sent):<30} returned {results[0]}/{results[1]}")
ring = RingList()
a = ring.push_back("a")
ring.push_back("b")
ring.push_front("z")
print("ring:", ring.values())
ring.remove(a)
print("ring after remove(a):", ring.values())
ring.remove(ring.sentinel.next)
ring.remove(ring.sentinel.prev)
print("ring after removing the rest:", ring.values(), "sentinel points at itself:",
ring.sentinel.next is ring.sentinel and ring.sentinel.prev is ring.sentinel)
random.seed(11)
for _ in range(2000):
p, s = PlainList(), SentinelList()
for _ in range(12):
op = random.choice(["insert_head", "delete_head", "delete_value"])
v = random.randint(0, 3)
try:
rp = getattr(p, op)(v) if op != "delete_head" else p.delete_head()
except IndexError:
rp = "empty"
try:
rs = getattr(s, op)(v) if op != "delete_head" else s.delete_head()
except IndexError:
rs = "empty"
assert rp == rs and p.values() == s.values()
print("2000 random operation sequences: plain and sentinel lists always agree")
s = SentinelList()
s.insert_head(5)
node, wrong = s.dummy, []
while node:
wrong.append(node.val)
node = node.next
print("iterating from the dummy by mistake:", wrong, "(the dummy's None leaks out)")
print("bytes per node (Python", sys.version.split()[0] + ", __slots__):",
sys.getsizeof(Node()), "singly,", sys.getsizeof(DNode()), "doubly")
Run with Python 3.12.15, it prints:
insert_head(3) plain: 3 -> None sentinel: dummy -> 3 -> None returned None/None
insert_head(2) plain: 2 -> 3 -> None sentinel: dummy -> 2 -> 3 -> None returned None/None
insert_head(1) plain: 1 -> 2 -> 3 -> None sentinel: dummy -> 1 -> 2 -> 3 -> None returned None/None
delete_value(1) plain: 2 -> 3 -> None sentinel: dummy -> 2 -> 3 -> None returned True/True
delete_value(3) plain: 2 -> None sentinel: dummy -> 2 -> None returned True/True
delete_head() plain: None sentinel: dummy -> None returned None/None
delete_value(9) plain: None sentinel: dummy -> None returned False/False
ring: ['z', 'a', 'b']
ring after remove(a): ['z', 'b']
ring after removing the rest: [] sentinel points at itself: True
2000 random operation sequences: plain and sentinel lists always agree
iterating from the dummy by mistake: [None, 5] (the dummy's None leaks out)
bytes per node (Python 3.12.15, __slots__): 48 singly, 56 doubly
Reading the ring one pointer write at a time
insert_after is four writes, and the order matters. The program below builds a ring from the sentinel S and nodes a, b, c, printing every prev and next after each write. push_back(a) on the empty ring is insert_after(sentinel.prev, a), and sentinel.prev is S itself. push_back(b) inserts after a, because a is now sentinel.prev. The last insertion puts c between a and b.
class DNode:
def __init__(self, label):
self.label = label
self.prev = None
self.next = None
sentinel = DNode("S")
sentinel.prev = sentinel.next = sentinel # empty ring points at itself
a, b, c = DNode("a"), DNode("b"), DNode("c")
nodes = [sentinel]
def show(step):
cells = [f"{n.label}[prev={n.prev.label if n.prev else '-'} next={n.next.label if n.next else '-'}]"
for n in nodes]
print(f"{step:<42}" + " ".join(cells))
def ring_values():
out, n = [], sentinel.next
while n is not sentinel:
out.append(n.label)
n = n.next
return out
def insert_after_traced(node, new):
nodes.append(new)
show(f"before inserting {new.label} after {node.label}")
new.prev, new.next = node, node.next
show(" new.prev, new.next = node, node.next")
node.next.prev = new
show(" node.next.prev = new")
node.next = new
show(" node.next = new")
show("empty ring")
insert_after_traced(sentinel.prev, a) # push_back(a): after sentinel.prev, which is S itself
insert_after_traced(sentinel.prev, b) # push_back(b): after a
insert_after_traced(a, c) # insert between a and b
print("walk from S:", ring_values())
Run, it prints:
empty ring S[prev=S next=S]
before inserting a after S S[prev=S next=S] a[prev=- next=-]
new.prev, new.next = node, node.next S[prev=S next=S] a[prev=S next=S]
node.next.prev = new S[prev=a next=S] a[prev=S next=S]
node.next = new S[prev=a next=a] a[prev=S next=S]
before inserting b after a S[prev=a next=a] a[prev=S next=S] b[prev=- next=-]
new.prev, new.next = node, node.next S[prev=a next=a] a[prev=S next=S] b[prev=a next=S]
node.next.prev = new S[prev=b next=a] a[prev=S next=S] b[prev=a next=S]
node.next = new S[prev=b next=a] a[prev=S next=b] b[prev=a next=S]
before inserting c after a S[prev=b next=a] a[prev=S next=b] b[prev=a next=S] c[prev=- next=-]
new.prev, new.next = node, node.next S[prev=b next=a] a[prev=S next=b] b[prev=a next=S] c[prev=a next=b]
node.next.prev = new S[prev=b next=a] a[prev=S next=b] b[prev=c next=S] c[prev=a next=b]
node.next = new S[prev=b next=a] a[prev=S next=c] b[prev=c next=S] c[prev=a next=b]
walk from S: ['a', 'c', 'b']
In each insertion the first write gives the new node both of its pointers while the old neighbours still point at their old partners. node.next.prev = new must come before node.next = new: after the last write, node.next means the new node, and the old right-hand neighbour would no longer be reachable by that expression. On the empty ring the same four writes work without a single None check, because S.next and S.prev both lead back to S. The final walk from S follows next pointers and prints ['a', 'c', 'b'].
Reading the output
- Each row applies the same call to both lists. The plain list shows
1 -> 2 -> 3 -> None; the sentinel list shows the same values behinddummy. The returned values and the contents agree on every row, includingdelete_value(1), which removes the head. In the plain list that was the extra branch; in the sentinel list it is the ordinary loop withprevstill ondummy. - The ring section shows a doubly linked list with a single sentinel.
push_frontinserts after the sentinel, andpush_backinserts aftersentinel.prev, which is the current last node.remove(node)is two assignments with noNonechecks, because every node'sprevandnextare always real nodes (possibly the sentinel itself). An empty ring is a sentinel pointing at itself, and the last line of the ring section checks that. - The random check applies 2000 random sequences of 12 operations to both singly linked versions and asserts the same results and contents after every step.
- The iteration mistake line shows the cost of a sentinel: start walking from
dummyinstead ofdummy.nextand the dummy's placeholderNoneappears as if it were data. - The last line reports
sys.getsizeof(the function that returns an object's own size in bytes, not counting the objects it refers to) for one slotted node object on this Python build: 48 bytes singly linked and 56 doubly linked. A sentinel costs exactly one node of that size per list, regardless of how many real nodes the list has.
Trade-offs the sentinel brings
In interviews the expected points are fewer special cases at the head and returning dummy.next; the memory cost per list is what decides whether to use one at scale, and the circular and two-sentinel variants are deeper material.
- Fewer branches, fewer bugs. Head insertion, head deletion and deletion of the only node need no special code. In a doubly linked ring, the checks for "is this the first node" and "is this the last node" disappear from insert and remove.
- One extra node of memory per list. For one long list that is nothing. For millions of tiny lists the overhead is per list and adds up, so the usual choice there is no sentinel. Two examples: a hash table keeps one small chain of entries per bucket (bucket: one slot of the table, holding every key that hashed to it), and a graph stored as an adjacency list keeps one list of neighbours per vertex. With a million buckets or vertices, a million sentinels is a million wasted nodes.
- Callers must skip it. Iteration starts at
dummy.next, length counting must not count it, and "is the list empty" becomesdummy.next is None. - Never read its value. It holds no data, so a search for any value, including the placeholder, must not look at it.
- Public API surface. If callers are handed node references, they can be handed the sentinel by mistake. Keep it private.
- Two sentinels or one. A doubly linked list can use a head sentinel and a tail sentinel (two extra nodes, no circular links), or one circular sentinel as above (one extra node). The circular form is shorter; the two-sentinel form keeps the first and last real node easy to recognise.
- In C or C++ the dummy can be a local variable (
Node dummy;) when it only exists for one function, so it costs no heap allocation at all, which is how many delete-by-value and merge functions use it.
Complexity
Insert at head: O(1) time and space for both versions. delete_value: O(n) time in both, O(1) extra space. The sentinel changes constants and code size, not the asymptotics (the growth rate of the cost as n gets large, which stays O(n) for the walk).
Common mistakes
- Returning
dummyinstead ofdummy.nextfrom a function that returns a head. - Letting the sentinel's value take part in comparisons.
- Allocating a sentinel per node-level operation in a hot loop instead of once per list.
- Forgetting to initialise the ring sentinel's
prevandnextto itself, which breaks the firstpush_back.
Running the code
docker run --rm -v "$PWD":/w -w /w python:3.12 python sentinel.py
Save the main listing as sentinel.py and the ring trace as ring_trace.py; run the second the same way. Both use only the standard library.
Implement a fixed-capacity queue on an array with enqueue, dequeue, peek, is_empty and is_full, using wrap-around indices. Walk through a sequence of operations that wraps past the end of the array.
Sample Answer
The idea in plain words
A fixed-size array is cheap and needs no allocation after creation, but a naive queue on it has a flaw: if dequeue shifts every remaining item one slot left, each dequeue costs O(n). A circular buffer (also called a ring buffer) avoids the shifting. Keep an index head for the oldest item. Dequeue just moves head forward by one. Enqueue writes at the first free slot, which is head + size. When an index would run past the last slot, wrap around to slot 0 using the remainder operator %: (index + 1) % capacity. The array is treated as a circle, so the freed slots at the front get reused.
The design choice that matters is how to tell empty from full. If you only store head and tail, both situations look like head == tail. The simplest fix, used below, is to store a size counter: empty is size == 0, full is size == capacity. The alternative is to leave one slot permanently unused, which costs one slot but needs no counter.
Approach, step by step
- State: an array
itemsof fixed length,head(index of the oldest item),size(how many items are stored). enqueue(v): if full, refuse (here: raiseOverflowError; in embedded code a returnedfalseis the usual choice). Otherwise write at(head + size) % capacityand increasesize.dequeue(): if empty, refuse. Otherwise readitems[head], clear the slot, sethead = (head + 1) % capacity, decreasesize.peek(): returnitems[head]without changing anything; refuse if empty.is_empty()andis_full()comparesizewith 0 and with the capacity.
The tail is never stored. It is always computed as (head + size) % capacity, which removes one value that could drift out of sync.
The code
import random
from collections import deque
class CircularQueue:
def __init__(self, capacity):
if capacity < 1:
raise ValueError("capacity must be at least 1")
self.items = [None] * capacity
self.head = 0 # index of the oldest item (next to leave)
self.size = 0 # number of items stored
def is_empty(self):
return self.size == 0
def is_full(self):
return self.size == len(self.items)
def enqueue(self, value):
if self.is_full():
raise OverflowError("queue is full")
tail = (self.head + self.size) % len(self.items) # first free slot
self.items[tail] = value
self.size += 1
def dequeue(self):
if self.is_empty():
raise IndexError("queue is empty")
value = self.items[self.head]
self.items[self.head] = None # drop the reference
self.head = (self.head + 1) % len(self.items) # wrap past the end
self.size -= 1
return value
def peek(self):
if self.is_empty():
raise IndexError("queue is empty")
return self.items[self.head]
def show(label, q, result=""):
tail = (q.head + q.size) % len(q.items)
print(f"{label:<13}{str(q.items):<27}head={q.head} tail={tail} size={q.size} {result}")
def walkthrough():
q = CircularQueue(4)
show("start", q)
for v in (10, 20, 30, 40):
q.enqueue(v); show(f"enqueue({v})", q)
try:
q.enqueue(50)
except OverflowError as e:
show("enqueue(50)", q, f"-> {e}")
show("dequeue()", q, f"-> {q.dequeue()}")
show("dequeue()", q, f"-> {q.dequeue()}")
q.enqueue(50); show("enqueue(50)", q) # lands in slot 0
q.enqueue(60); show("enqueue(60)", q) # lands in slot 1, queue is full again
show("peek()", q, f"-> {q.peek()}")
out = []
while not q.is_empty():
out.append(q.dequeue())
show("drain", q, f"-> {out}")
try:
q.dequeue()
except IndexError as e:
show("dequeue()", q, f"-> {e}")
def random_check():
random.seed(3)
for _ in range(500):
cap = random.randint(1, 6)
q, ref = CircularQueue(cap), deque()
for _ in range(80):
if random.random() < 0.5:
if len(ref) == cap:
assert q.is_full()
try:
q.enqueue(0); assert False
except OverflowError:
pass
else:
v = random.randint(0, 99)
q.enqueue(v); ref.append(v)
elif ref:
assert q.peek() == ref[0] and q.dequeue() == ref.popleft()
else:
assert q.is_empty()
assert q.size == len(ref)
print("500 random runs with capacities 1 to 6 match collections.deque")
if __name__ == "__main__":
walkthrough()
random_check()
Run, it prints:
start [None, None, None, None] head=0 tail=0 size=0
enqueue(10) [10, None, None, None] head=0 tail=1 size=1
enqueue(20) [10, 20, None, None] head=0 tail=2 size=2
enqueue(30) [10, 20, 30, None] head=0 tail=3 size=3
enqueue(40) [10, 20, 30, 40] head=0 tail=0 size=4
enqueue(50) [10, 20, 30, 40] head=0 tail=0 size=4 -> queue is full
dequeue() [None, 20, 30, 40] head=1 tail=0 size=3 -> 10
dequeue() [None, None, 30, 40] head=2 tail=0 size=2 -> 20
enqueue(50) [50, None, 30, 40] head=2 tail=1 size=3
enqueue(60) [50, 60, 30, 40] head=2 tail=2 size=4
peek() [50, 60, 30, 40] head=2 tail=2 size=4 -> 30
drain [None, None, None, None] head=2 tail=2 size=0 -> [30, 40, 50, 60]
dequeue() [None, None, None, None] head=2 tail=2 size=0 -> queue is empty
500 random runs with capacities 1 to 6 match collections.deque
Worked trace of a wrap-around
Capacity 4. tail in the output is the slot the next enqueue will use.
- Four enqueues fill slots 0 to 3. The tail has wrapped back to 0 and
size=4, so the queue is full. The extraenqueue(50)is refused and nothing changes. - Two dequeues return 10 and 20.
headmoves to 2 and slots 0 and 1 are free again. enqueue(50)goes to slot(2 + 2) % 4 = 0, andenqueue(60)goes to slot(2 + 3) % 4 = 1. This is the wrap past the end of the array: the logical order is 30, 40, 50, 60, which sits in slots 2, 3, 0, 1.peek()returns 30 (slot 2), the oldest item. Draining returns 30, 40, 50, 60 in arrival order. After the drainheadis 2 again withsize=0: the position of an empty queue does not matter, onlysizedoes.- A dequeue on the empty queue is refused.
Leaving one slot unused instead of counting
Without a size counter, head == tail has to mean exactly one thing. Make it mean empty, and never let the queue fill every slot: with N slots it holds at most N - 1 items, and it counts as full when advancing tail by one would land on head, that is (tail + 1) % N == head. The reason is in the trace: with 4 slots and 3 items, a fourth write would push tail back to slot 0, the same slot as head, and a full queue would then look exactly like an empty one. Giving up one slot keeps the two states apart.
class OneSlotQueue:
"""Ring buffer that keeps one slot unused, so head == tail can only mean empty."""
def __init__(self, slots):
if slots < 2:
raise ValueError("need at least 2 slots")
self.items = [None] * slots
self.head = 0 # slot of the oldest item
self.tail = 0 # slot where the next item will be written
def is_empty(self):
return self.head == self.tail
def is_full(self):
return (self.tail + 1) % len(self.items) == self.head
def enqueue(self, value):
if self.is_full():
raise OverflowError("queue is full")
self.items[self.tail] = value
self.tail = (self.tail + 1) % len(self.items)
def dequeue(self):
if self.is_empty():
raise IndexError("queue is empty")
value, self.items[self.head] = self.items[self.head], None
self.head = (self.head + 1) % len(self.items)
return value
def show(label, q, note=""):
print(f"{label:<12}{str(q.items):<28}head={q.head} tail={q.tail} "
f"empty={q.is_empty()} full={q.is_full()} {note}")
q = OneSlotQueue(4) # 4 slots, at most 3 items
show("start", q)
for v in (10, 20, 30):
q.enqueue(v)
show(f"enqueue({v})", q)
print("a 4th item would move tail to", (q.tail + 1) % 4, "which equals head", q.head, "so it would look empty")
try:
q.enqueue(40)
except OverflowError as e:
print("enqueue(40) ->", e)
print("dequeue() ->", q.dequeue()); show("", q)
q.enqueue(40); show("enqueue(40)", q, "<- tail wrapped to slot 0")
print("drain ->", [q.dequeue() for _ in range(3)]); show("", q)
try:
OneSlotQueue(1)
except ValueError as e:
print("OneSlotQueue(1) ->", e)
Run, it prints:
start [None, None, None, None] head=0 tail=0 empty=True full=False
enqueue(10) [10, None, None, None] head=0 tail=1 empty=False full=False
enqueue(20) [10, 20, None, None] head=0 tail=2 empty=False full=False
enqueue(30) [10, 20, 30, None] head=0 tail=3 empty=False full=True
a 4th item would move tail to 0 which equals head 0 so it would look empty
enqueue(40) -> queue is full
dequeue() -> 10
[None, 20, 30, None] head=1 tail=3 empty=False full=False
enqueue(40) [None, 20, 30, 40] head=1 tail=0 empty=False full=True <- tail wrapped to slot 0
drain -> [20, 30, 40]
[None, None, None, None] head=0 tail=0 empty=True full=False
OneSlotQueue(1) -> need at least 2 slots
Reading the output: tail is the slot the next write uses. After the third enqueue the queue is full while one slot is still empty, which is the price of this design. After dequeue() returns 10, head moves to 1 and enqueue(40) writes into slot 0, so tail wraps to 0 and the queue is full again with head=1. The head == tail state occurs only in the first and last rows, where the queue is empty.
Complexity
Every operation is O(1) time: a few comparisons, one index calculation and one array access. Space is O(capacity), fixed at construction, with O(1) extra for head and size. Nothing allocates during enqueue or dequeue, which is why this shape is common in embedded code, device drivers and audio or network buffers.
Edge cases and common mistakes
- Capacity 1:
headstays 0,(0 + 1) % 1 == 0, and the queue alternates between empty and full. The random check includes capacity 1. - Empty versus full ambiguity when only two indices are kept. Either keep
size, or keep one slot unused and call the queue full when(tail + 1) % capacity == head, as the one-slot version above does. - Forgetting the modulo on
headindequeue, which runs off the end of the array. - Using
head + sizewithout the modulo when computing the write slot. - Leaving old references in dequeued slots. In Python or Java this keeps objects alive longer than needed, which is why
dequeueclears the slot. - Computing
sizeastail - headwithout handling the wrapped case (tail smaller than head gives a negative number).
Running the code
python circular_queue.py
Python 3.12, standard library only.
Why can traversing a linked list be much slower than traversing an array on modern CPUs even when both are O(n)? Explain the hardware effects, then describe the techniques you would use to reduce pointer-chasing costs in a linked structure that must stay linked, such as unrolling or pooling.
Sample Answer
The idea in plain words
Both traversals do n steps, so Big-O calls them equal. The hardware does not. A CPU does not read memory one number at a time: it fetches a cache line (a block of consecutive bytes, 64 bytes on most x86-64 and many ARM CPUs, 128 on some) into a small, fast cache, and anything already in the cache is cheap to read again. Main memory is far slower than the cache, so speed comes from reading data that is already there or arriving early.
An array makes that easy: its elements are neighbours, so one fetched line brings in several elements, and the addresses of the next elements are known in advance. (Latency is the waiting time for one request to memory; bandwidth is how much data per second can flow once requests are flowing. A list traversal is limited by latency, an array scan mostly by bandwidth.) A linked list makes it hard for two reasons: its nodes can be anywhere in memory, and the address of the next node is stored inside the current node, so the CPU cannot even start the next load until the current one has finished. That second effect, a chain of dependent loads, is the core of pointer-chasing cost.
The hardware effects
- Spatial locality and cache lines. Reading
a[i]fetches the whole 64-byte line it sits in, which holds up to 15 of the following 4-byte ints (15 ifa[i]is the first int of its line, fewer otherwise), for free. A node in a scattered list brings in its own line and usually nothing else you will use. - Prefetching. The CPU watches the sequence of addresses and, when it sees a steady stride (a fixed gap between successive addresses) such as
a[0], a[1], a[2], fetches the following lines before they are asked for. It can do that for an array. For a list it can only guess if the nodes happen to sit at regular spacing in memory. - Memory-level parallelism. An out-of-order CPU (one that starts later instructions while an earlier one waits for memory, as long as the later ones do not depend on it) can have many loads in flight at once if their addresses do not depend on each other. Array loads are independent, so the memory latency is overlapped. List loads form a chain, so the total time is roughly n times the latency of one trip to wherever the node lives.
- TLB. Programs use virtual addresses, and each access needs a translation to a physical page. The TLB (translation lookaside buffer) is a small cache of recent translations. A page is commonly 4 KiB. An array walk crosses into a new page every 4096 bytes. Scattered nodes can land in a different page on almost every step, and a TLB miss triggers a walk of the page tables (the operating system's map from virtual pages to physical pages, stored in ordinary memory), which is extra memory reads.
- Branch prediction. The loop branch
while nodeis easy to predict for both structures, so branch prediction is not the main reason lists are slower. It matters indirectly: when the loop has a data-dependent branch (for exampleif node.value > x), the condition depends on the loaded value. For an array the CPU runs ahead and resolves it early. For a list the value arrives late, so a misprediction is discovered late and more speculative work is thrown away. Speculative work is what the CPU executes on a guess about which way a branch will go; if the guess is wrong, that work is discarded.
A model that counts these effects
The program replays address sequences through a simulated cache (512 lines of 64 bytes, fully associative, least-recently-used replacement) and a simulated TLB (64 pages of 4096 bytes), for 65536 4-byte values. "Fully associative" means any line may sit in any cache slot; real caches let each line live in only a few slots, so real miss counts are somewhat higher when many lines map to the same slots. "Least-recently-used replacement" means that when the cache is full, the line untouched for the longest time is evicted to make room. With these two rules the model counts only the misses caused by the layout itself. The first table below shows what layout alone does to the miss counts; the second applies the same idea to chains of segments. It is a simplified model: it ignores the prefetcher, real associativity and memory timing, so its numbers show the effect of layout, not the speed of any particular CPU.
import random
from collections import OrderedDict
LINE = 64 # bytes per cache line
PAGE = 4096 # bytes per page
CACHE_LINES = 512 # model cache: 512 lines = 32 KiB, fully associative, LRU
TLB_ENTRIES = 64 # model TLB: 64 page translations, fully associative, LRU
class LRU:
def __init__(self, capacity):
self.capacity, self.items, self.misses = capacity, OrderedDict(), 0
def touch(self, key):
if key in self.items:
self.items.move_to_end(key)
return
self.misses += 1
self.items[key] = True
if len(self.items) > self.capacity:
self.items.popitem(last=False)
def run(addresses):
"""Replay a list of (address, size) reads. Returns (cache misses, TLB misses)."""
cache, tlb = LRU(CACHE_LINES), LRU(TLB_ENTRIES)
for addr, size in addresses:
for line in range(addr // LINE, (addr + size - 1) // LINE + 1):
cache.touch(line)
for page in range(addr // PAGE, (addr + size - 1) // PAGE + 1):
tlb.touch(page)
return cache.misses, tlb.misses
N = 1 << 16 # 65536 elements, all 4-byte ints
rng = random.Random(1)
scattered = list(range(N))
rng.shuffle(scattered) # node k of the list lives in slot scattered[k]
layouts = [] # (name, reads, dependent loads)
layouts.append(("array of int32", [(4 * i, 4) for i in range(N)], 0))
layouts.append(("list, 16 B nodes, in list order", [(16 * i, 16) for i in range(N)], N))
layouts.append(("list, 16 B nodes, scattered", [(16 * s, 16) for s in scattered], N))
layouts.append(("list, 8 B nodes (32-bit index), in order", [(8 * i, 8) for i in range(N)], N))
layouts.append(("list, 8 B nodes (32-bit index), scattered", [(8 * s, 8) for s in scattered], N))
CHUNK = 14 # 14 ints (56 B) + 8 B next pointer = one 64 B line
chunks = (N + CHUNK - 1) // CHUNK
layouts.append(("unrolled list, 64 B nodes, scattered", [(64 * s, 64) for s in rng.sample(range(chunks), chunks)], chunks))
print(f"{N} elements; model cache {CACHE_LINES} lines of {LINE} B, TLB {TLB_ENTRIES} pages of {PAGE} B")
print(f"{'layout':<44}{'cache misses':>13}{'TLB misses':>12}{'dependent loads':>17}")
for name, reads, chases in layouts:
cm, tm = run(reads)
print(f"{name:<44}{cm:>13}{tm:>12}{chases:>17}")
print()
print("segment chain: 1 MiB of payload split into segments of s bytes (+8 B next pointer), segments scattered")
print(f"{'segment payload s':>18}{'segments':>10}{'cache misses':>14}{'dependent loads':>17}")
TOTAL = 1 << 20
for s in (16, 64, 256, 4096):
seg = s + 8
count = TOTAL // s
slots = list(range(count))
rng.shuffle(slots)
stride = (seg + 15) // 16 * 16 # each segment is placed on a 16-byte boundary
cm, _ = run([(stride * k, seg) for k in slots])
print(f"{s:>18}{count:>10}{cm:>14}{count:>17}")
cm, _ = run([(i * 64, 64) for i in range(TOTAL // 64)])
print(f"{'contiguous buffer':>18}{1:>10}{cm:>14}{0:>17}")
print()
print("passes over the same 65536 scattered values: walk the list p times, or convert once and scan p times")
print(f"{'passes p':>9}{'list misses':>13}{'convert misses':>16}")
ARRAY_BASE = 1 << 30 # the new array lives far from the nodes
node_reads = [(16 * s, 16) for s in scattered]
array_reads = [(ARRAY_BASE + 4 * i, 4) for i in range(N)]
for p in (1, 2, 3):
list_cm, _ = run(node_reads * p)
convert_cm, _ = run(node_reads + array_reads + array_reads * p) # one chase, writes, then p scans
print(f"{p:>9}{list_cm:>13}{convert_cm:>16}")
Run with Python 3.12.15, it prints:
65536 elements; model cache 512 lines of 64 B, TLB 64 pages of 4096 B
layout cache misses TLB misses dependent loads
array of int32 4096 64 0
list, 16 B nodes, in list order 16384 256 65536
list, 16 B nodes, scattered 63945 49244 65536
list, 8 B nodes (32-bit index), in order 8192 128 65536
list, 8 B nodes (32-bit index), scattered 61844 33000 65536
unrolled list, 64 B nodes, scattered 4682 627 4682
segment chain: 1 MiB of payload split into segments of s bytes (+8 B next pointer), segments scattered
segment payload s segments cache misses dependent loads
16 65536 65056 65536
64 16384 32372 16384
256 4096 20310 4096
4096 256 16627 256
contiguous buffer 1 16384 0
passes over the same 65536 scattered values: walk the list p times, or convert once and scan p times
passes p list misses convert misses
1 63945 72137
2 127882 76233
3 191819 80329
How to read it:
- Array: 4096 misses = 65536 x 4 B / 64 B, one miss per line, and 64 TLB misses (one per page). No dependent loads.
- Perfectly laid-out list with 16-byte nodes (a 4-byte value, padding, an 8-byte pointer on a 64-bit machine): 16384 misses, four times the array, because each element drags 16 bytes with it instead of 4. It still has 65536 dependent loads.
- Scattered list: 63945 misses, almost one per node, and 49244 TLB misses, because the 1 MiB working set (the memory the loop touches) is far bigger than the 32 KiB model cache and the 64-page TLB. This is the case that "linked lists are slow" refers to.
Reducing pointer-chasing cost in a structure that must stay linked
In interviews the usual answers are pooling and unrolling, with a short mention of why scattered nodes hurt. Packing, software prefetch and the conversion trade-off in item 5 are deeper material, asked mostly for systems and performance roles.
- Pool the nodes (allocate them from one contiguous block, called an arena, handing out the next free slot for each new node, in the order you will traverse them). The table shows 16384 misses and 256 TLB misses for the in-order layout against 63945 and 49244 scattered. Pooling also removes per-node
mallocoverhead. Inserts and deletes scramble the order over time, so rebuild (compact) the pool in list order now and then; that is one O(n) pass. - Pack the nodes. Use 32-bit indices into the pool instead of 64-bit pointers, and drop padding: 8-byte nodes halve the in-order misses to 8192. The cost is an index-to-address step and a limit of about 4 billion nodes. Keep the hot fields (value, next) together and move cold fields elsewhere.
- Unroll the list: store several elements in each node. With 14 ints and a next pointer filling one 64-byte line, the scattered unrolled list takes 4682 misses and 4682 dependent loads, against 63945 and 65536. Inserts shift elements inside one chunk, and chunks run partly empty.
- Prefetch in software. When each node needs real work, issue a prefetch for the next node before processing the current one (GCC and Clang offer
__builtin_prefetch(address), which asks the CPU to start loading that address into the cache without stalling the program and, per the GCC documentation, does not fault on an invalid address), or walk several independent lists in an interleaved loop so their latencies overlap. - Give up pointer chasing for read-heavy phases. Converting a list to an array costs one chase and then every later pass is a sequential scan. Any single pass over a scattered list pays one full chase, because every node must be loaded. Reversing the list in place is one such pass: it does its work while it chases and needs no second structure. Converting to an array is also one chase, plus writing the new array. So the conversion only pays off when the array is scanned more than once afterwards. The last table printed above counts it for the 65536 scattered values: one pass costs 63945 misses on the list and 72137 with the conversion (63945 for the chase, 4096 to write the array, 4096 to scan it), so the list wins for one pass. At two passes the list costs 127882 and the conversion 76233, and the gap widens with every further pass.
Chaining variable-length segments
A buffer made of linked segments (for example a message stored as a chain of separately allocated chunks) pays a fixed cost per segment: one dependent pointer load, a fresh cache line, and the loop overhead around a copy of a few bytes. The second table in the output shows it for 1 MiB of payload: 16-byte segments cause 65056 misses and 65536 dependent loads, against 16384 misses and no chase for a contiguous buffer. At 4096 bytes per segment, 16627 misses and 256 loads remain, close to the contiguous case. So throughput falls as segments shrink: keep segments large, or coalesce small ones into a contiguous buffer before processing.
Complexity and decision
Traversal is O(n) time and O(1) extra space for both structures; only the constant differs. Use an array (or a chunked list) for scan-heavy work. Keep a plain linked list only when you need O(1) splicing at held positions, stable node addresses, or intrusive membership in several lists (an intrusive list keeps its link pointers inside the object itself, one pair per list, so one object can sit in several lists at once without any wrapper nodes), and then pool and compact it.
Common mistakes
- Treating equal Big-O as equal speed.
- Believing a list is faster for insertion without counting the walk to the insertion point.
- Assuming pooling fixes locality for good (the list order drifts from the memory order).
- Benchmarking a list that was just built (nodes allocated in order and still warm) and generalizing to a list that has lived for hours.
Running the code
docker run --rm -v "$PWD":/w -w /w python:3.12 python locality_model.py
Save the listing as locality_model.py. It uses only the standard library.
Simulate a round-robin scheduler: given tasks as (id, duration) pairs and a time quantum q, return each task's finish time in completion order. Explain which structure you use for the ready queue.
Sample Answer
The idea
Round-robin scheduling gives every unfinished task the processor for at most one fixed slice (the time quantum, q), then sends it to the back of the line so the next task gets a turn. "Front of the line, back of the line" is exactly a queue: first in, first out (FIFO). The ready queue holds the tasks that still need time; each turn you take the front, run it for min(q, time_left), and either put it at the back (work remains) or record its finish time (done). The clock advances by the time actually run, so a task shorter than the quantum gives the processor back early.
Which structure for the ready queue
Use collections.deque (a double-ended queue). The notation O(1) means the number of steps does not grow with the number of items, O(n) means it grows in proportion to the n items, and amortized O(1) means constant when averaged over many calls even if an occasional call is slower. A deque is O(1) at both ends. Dequeuing from the front and enqueuing at the back are both O(1). A Python list works for the back (append is amortized O(1)) but list.pop(0) shifts every remaining element, so it is O(n) per turn. A linked list with head and tail pointers would give the same O(1) cost but needs a node allocation per turn.
Brute force is a for-loop over a list that keeps sweeping all tasks and skips finished ones. It gives the same answers but rescans finished tasks on every sweep and is hard to extend (a new arrival has no natural place). The sweep_all function in the listing is that version: on the example below it makes 12 task visits, 5 of them to tasks that had already finished, while the queue does only the 7 turns that actually happen.
Steps
- Put every
(task_id, duration)into the queue in input order. Rejectq <= 0(a zero quantum would loop forever). - While the queue is not empty: pop the front,
run = min(q, left), addrunto the clock, subtract it fromleft. - If
left > 0, append the task to the back. Otherwise append(task_id, clock)to the results.
Code
from collections import deque
import random
def round_robin(tasks, quantum, trace=False):
"""tasks: list of (task_id, duration), all ready at time 0.
Returns [(task_id, finish_time), ...] in completion order."""
if quantum <= 0:
raise ValueError("quantum must be positive")
ready = deque(tasks) # FIFO ready queue of (task_id, time_left)
clock = 0
finished = []
while ready:
task_id, left = ready.popleft()
run = min(quantum, left) # a task shorter than the quantum gives the CPU back early
clock += run
left -= run
if left > 0:
ready.append((task_id, left)) # back of the line
else:
finished.append((task_id, clock))
if trace:
print(f"t={clock:2d} ran {task_id} for {run} "
f"left={left} queue={list(ready)} done={finished}")
return finished
def reference(tasks, quantum):
"""Slow check: sweep the unfinished tasks in order, round after round."""
left = dict(tasks)
clock, out = 0, []
while left:
for task_id in [t for t, _ in tasks if t in left]:
run = min(quantum, left[task_id])
clock += run
left[task_id] -= run
if left[task_id] == 0:
out.append((task_id, clock))
del left[task_id]
return out
def sweep_all(tasks, quantum):
"""Brute force: every round visits every task, finished or not, and skips the finished ones."""
left = dict(tasks)
clock, out, visits, wasted = 0, [], 0, 0
while len(out) < len(tasks):
for task_id, _ in tasks:
visits += 1
if left[task_id] == 0 and any(t == task_id for t, _ in out):
wasted += 1 # a finished task looked at again
continue
run = min(quantum, left[task_id])
clock += run
left[task_id] -= run
if left[task_id] == 0:
out.append((task_id, clock))
return out, visits, wasted
if __name__ == "__main__":
tasks = [("A", 5), ("B", 3), ("C", 8), ("D", 2)]
print(round_robin(tasks, 3, trace=True))
turns = sum(max(1, -(-d // 3)) for _, d in tasks) # ceil(d / q), at least 1 turn per task
total = sum(d for _, d in tasks)
print(f"turns taken: {turns}; bound T/q + n = {total}/3 + {len(tasks)} = {total / 3 + len(tasks):.1f}")
order, visits, wasted = sweep_all(tasks, 3)
assert order == round_robin(tasks, 3)
print(f"sweep-everything version: {visits} task visits, {wasted} of them to already finished tasks")
rng = random.Random(1)
for _ in range(300):
n = rng.randint(1, 6)
case = [(f"T{i}", rng.randint(0, 9)) for i in range(n)]
q = rng.randint(1, 5)
assert round_robin(case, q) == reference(case, q), (case, q)
assert sweep_all(case, q)[0] == round_robin(case, q), (case, q)
print("300 random cases (durations 0 to 9) match the reference and the sweep-everything version")
print(round_robin([("Z", 0), ("Y", 4)], 3))
try:
round_robin(tasks, 0)
except ValueError as err:
print("ValueError:", err)
The reference function is a slower, simpler version used only for checking: it sweeps the unfinished tasks round after round. The assert loop compares it, and the sweep-everything version, with the queue version on 300 random task lists (durations 0 to 9) and stops with an error on the first disagreement.
Output
t= 3 ran A for 3 left=2 queue=[('B', 3), ('C', 8), ('D', 2), ('A', 2)] done=[]
t= 6 ran B for 3 left=0 queue=[('C', 8), ('D', 2), ('A', 2)] done=[('B', 6)]
t= 9 ran C for 3 left=5 queue=[('D', 2), ('A', 2), ('C', 5)] done=[('B', 6)]
t=11 ran D for 2 left=0 queue=[('A', 2), ('C', 5)] done=[('B', 6), ('D', 11)]
t=13 ran A for 2 left=0 queue=[('C', 5)] done=[('B', 6), ('D', 11), ('A', 13)]
t=16 ran C for 3 left=2 queue=[('C', 2)] done=[('B', 6), ('D', 11), ('A', 13)]
t=18 ran C for 2 left=0 queue=[] done=[('B', 6), ('D', 11), ('A', 13), ('C', 18)]
[('B', 6), ('D', 11), ('A', 13), ('C', 18)]
turns taken: 7; bound T/q + n = 18/3 + 4 = 10.0
sweep-everything version: 12 task visits, 5 of them to already finished tasks
300 random cases (durations 0 to 9) match the reference and the sweep-everything version
[('Z', 0), ('Y', 4)]
ValueError: quantum must be positive
Worked trace
Tasks A=5, B=3, C=8, D=2 with q=3. Each row above is one turn; t is the clock after the turn, and queue is the line after the task has been put back (or dropped). In words: A runs 3 and has 2 left, so it goes behind D. B needs exactly 3, so it finishes at 6. C runs 3 and has 5 left. D needs only 2, so the turn ends early at 11. A finishes at 13 (2 more units), and C gets the processor alone for two more turns (3 units, then 2) and finishes at 18. The total work is 5 + 3 + 8 + 2 = 18, and the last finish time is 18 because the processor never idled. The completion order is B, D, A, C, which differs from the input order: that is the point of round-robin, short jobs finish early.
Complexity
Each task needs ceil(duration / q) turns (ceil rounds up, and a zero-length task still takes one turn). Rounding up adds less than 1 to duration / q, and a zero-length task takes its one turn, so a task takes at most duration / q + 1 turns. Summing over the tasks, the number of turns is at most T / q + n, where T is the total duration (the sum of the duration / q parts) and n is the number of tasks (the sum of the + 1 parts). For the example the code prints 7 turns against a bound of 10.0. Every turn does O(1) deque work, so time is O(T / q + n) (for q = 1 that is O(T + n)). Space is O(n) for the queue and the result list.
Edge cases and common mistakes
- Duration shorter than the quantum: advance the clock by the real run time (
min(q, left)), not by q. Adding q is the commonest bug. It makes every finish time after the first short turn too late (on the example D would finish at 12 instead of 11, while B, which uses its full slice, stays at 6). - Duration exactly divisible by q (B above):
leftis 0 after the turn, so it must finish, not be requeued with 0 left. - Zero-length task: finishes immediately at the current clock without moving time (
Zin the last run). - One task: runs repeatedly alone; finish equals its duration.
- Quantum of 0 or less: reject it.
- Using
pop(0)on a list: correct output, but O(n) per turn. - Returning finish times in input order instead of completion order: the question asks for completion order.
Follow-ups
A task that is preempted (stopped by the scheduler before it has finished, so that another task can run) goes to the back of the line. Tasks arriving at different times need an arrival-sorted list and a check at each turn for tasks that arrived during the slice (they join the back, and commonly a just-preempted task goes behind arrivals that came in during its slice). Context-switch cost (the time the processor spends saving one task's state and loading the next one's) adds a fixed overhead to the clock per turn, which is why a tiny q hurts throughput (the number of tasks completed per unit of time). Turnaround time is a task's finish time minus its arrival time, and waiting time is the turnaround time minus the time the task actually ran; here every arrival is 0, so turnaround equals the finish time. Priorities replace the single queue with one queue per level or a heap.
Running the code
Save the code as round_robin.py.
Run: python round_robin.py (Python 3.12, standard library only)
Unlock Full Question Bank
Get access to all 16 Linked Lists, Stacks, and Queues interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.