Linked lists and the doubly linked list
- Build and walk a singly linked list by hand, say what its O(1) insert at the front buys against a Python list and what it costs, and reach for a list, a deque or a dict when they do the job better
- Change pointers in an order that never loses the rest of the list, for an insert, a delete and a reverse in place, with a dummy head that gives the first node a node before it
- Find the middle, the k-th node from the end and the first node of a cycle with two pointers at two speeds, and explain why the pointers must meet and why a second walk from the head finds where the cycle starts
- Find where two lists meet by comparing nodes and not values, first with a set and then in O(1) extra memory
- Build a doubly linked list with a sentinel at each end, unlink and move a node in O(1), and find nodes through a dict
- Answer the follow-ups with numbers, from two lists that may loop to merging sorted lists, lists too long for recursion, copying a list with extra pointers and why arrays usually win
Redirect chains, the way the coding round asks
Intersection of Two Linked Lists is on Airbnb's LeetCode tag lists (2 sources), a write-up of a senior Airbnb onsite loop lists finding where two linked lists with cycles overlap (1 source), and a candidate was handed two lists that each may or may not loop (1 report). This lesson's practice problem is that shape, on a link service's redirect chains, in three levels:
drop_hops(head, blocked)andreverse_chain(head): change one chain in place, on 20,000 hops, without recursion.first_shared(a, b): the first hop two chains share, comparing hops and not urls, in O(1) extra memory.loop_start(head), andfirst_shared(a, b)when either chain may loop.
Call Returns drop_hops(a, {"track.example/1", "track.example/2"})the hop link.example/a, now pointing attrack.example/9reverse_chainof hops 1, 2 and 3hop 3, now pointing at hop 2 first_shared(a, b)the hop track.example/9, one object on both chainsloop_startof a chain that loops backthe loop's first hop
The lesson builds it from the pointers up: nodes and what they cost, pointer order, reversing, two speeds, cycles, where two lists meet, and doubly linked lists. 16 steps end with a small task in the editor.
A list is nodes joined by pointers
Python has no linked list type, and interviewers know it. When a question is about one, it hands you a small class for the nodes, and the question is about the pointers between them.
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def values(head):
out, node = [], head
while node is not None:
out.append(node.val)
node = node.next
return out
head = Node(3, Node(1, Node(4)))
print(values(head))
[3, 1, 4]
In memory, that list is three separate objects, each pointing at the next:
Three separate objects. Each holds a value and a pointer to the next node, and the last one points at None.
A node holds a value and a pointer, next: a reference to the node after it, or None at the end. The list is known by its first node, the head. None is the empty list.
There's no length and no index. To reach anything, you start at the head and follow next, the way values does.
values tests node, not node.next. Test node.next and the walk stops one node early:
def values_wrong(head):
out, node = [], head
while node.next is not None:
out.append(node.val)
node = node.next
return out
print(values_wrong(head))
[3, 1]
On the empty list it's worse: node is None, and None.next raises AttributeError: 'NoneType' object has no attribute 'next'.
In the editor, write length(head). It prints the length of a three-node list and of the empty list.
A walk around a cycle never ends, so give every walk a limit
A list can loop back on itself, and then a walk never ends.
def values(head, limit=10_000):
out, node = [], head
while node is not None:
if len(out) == limit:
raise ValueError(f"more than {limit} nodes: a cycle, or a very long list")
out.append(node.val)
node = node.next
return out
loop = Node(3, Node(1, Node(4)))
loop.next.next.next = loop.next
values(loop, limit=10)
The 4 now points back at the 1. What does values(loop, limit=10) do?
A pointer makes the front cheap, and costs the index
A linked list and a Python list trade costs. Here is each side of the trade, measured on Python 3.12 on an M1 Pro laptop.
def linked(vals):
head = None
for v in reversed(vals):
head = Node(v, head)
return head
print(values(linked([3, 1, 4, 1, 5])))
[3, 1, 4, 1, 5]
linked builds a list from the back, adding each value at the front with head = Node(v, head). Each add is one new node and one pointer. Nothing already in the list moves. The rest of this lesson builds its lists with linked.
A Python list keeps its items side by side in one block of memory. To make room at the front, it shifts every item one place, and the Python tutorial says that's why inserting at the front is slow:
before after All 5 items, in green, moved one place to make room.
One new node and one new pointer. Nothing else moves.
Here is the cost of one insert at the front of n items, the median of 5 runs of 1,000 inserts:
| n | Python list, µs | linked list, µs | deque, µs |
|---|---|---|---|
| 1,000 | 0.226 | 0.096 | 0.017 |
| 10,000 | 1.617 | 0.096 | 0.017 |
| 100,000 | 17.493 | 0.099 | 0.016 |
| 1,000,000 | 194.362 | 0.101 | 0.017 |
The calls are xs.insert(0, x), head = Node(x, head) and dq.appendleft(x).
From 10,000 items up, ten times the items made the list's insert about ten times slower: O(n). The linked list didn't move: O(1).
And collections.deque, a double-ended queue written in C, was about six times faster again than the linked list built in Python.
A linked list has no index, so the k-th node is k steps from the head
A Python list jumps to any slot. A linked list has to walk there.
xs Reading the item at position n // 2, median of 5 runs:
Reading the middle item of a million-item linked list took 8.5 ms. About how long did xs[k] take on a Python list?
Each node is a whole object: 48 to 80 bytes, and slower to walk
Every node costs memory, and every step costs time.
That's measured with tracemalloc, Python's memory tracer. Every value is None, so only the structure counts.
A list stores one pointer per item. A linked list stores an object per item, and the object holds the pointer. __slots__ = ("val", "next") on the class drops the storage each object keeps for its attributes. It's a detail: the point is that a node is a whole Python object.
Walking costs more too. Adding up 1,000,000 values, median of 5 runs:
Adding up a million values: sum(xs) took 3 ms. About how long did walking the nodes take?
The O(1) insert needs the node in hand
Insert in the middle and see where the claim stops:
Insert in the middle of a million items. Which is faster: xs.insert(n // 2, x) on a Python list, or a linked list that walks to the middle first?
In Python, a list, a deque or a dict usually does the job
Most of the time, Python already has a better tool than a list you link by hand:
- A stack: a
list, pushing and popping at the end. - A queue, or anything added and removed at both ends:
collections.deque. - Look up by key, in an order you change: a
dict, or anOrderedDict. - Nodes you link by hand: when the question gives you nodes, or when you hold references to nodes and splice them in and out of the middle.
In an interview, say the first three out loud when they fit. Then write the pointers anyway, because the pointers are what the question tests.
Change pointers in an order that never loses the rest
Most of the work on a linked list is moving one or two pointers. The skill is the order you move them in.
def insert_after(node, val):
# the new node takes over node's old next
node.next = Node(val, node.next)
def delete_after(node):
# step over the node after
node.next = node.next.next
head = linked([3, 1, 4])
insert_after(head, 9)
print(values(head))
delete_after(head)
print(values(head))
[3, 9, 1, 4]
[3, 1, 4]
insert_after makes the new node point at 1 first, and only then moves 3's pointer to it:
delete_after changes one pointer so it skips a node:
delete_after takes the node before the one to delete. In a singly linked list a node doesn't know which node points at it. So you can only unhook a node from the node before it, its predecessor. The doubly linked list further down lifts that limit.
In the editor, write insert_sorted(head, val), which returns the head because a small value becomes the new one. It inserts 5, then 0, into a sorted list.
Overwrite a pointer only once something else holds what it pointed at
Node(val, node.next) reads the old node.next before the assignment overwrites it. Write the insert in two steps the other way round and the rest of the list is gone:
def insert_after_wrong(node, val):
new = Node(val)
node.next = new
# node.next is new by now, so new points at itself
new.next = node.next
head = linked([3, 1, 4])
insert_after_wrong(head, 9)
values(head, limit=10)
ValueError: more than 10 nodes: a cycle, or a very long list
The 9 points at itself, and nothing points at the 1 anymore:
Without the limit, that walk appends 9 forever. So here is the rule for every pointer change: before you overwrite a pointer, make sure something else still holds what it pointed at.
In the editor, write swap_first_two(head): move the nodes, not the values, in an order that never loses the rest. It prints the swapped list, and whether the old head is now second.
A dummy head gives the first node a node before it
Remove every node whose value is in a set unwanted. You delete through the predecessor, so you look one node ahead, at node.next. That works for every node but the head, which has no predecessor. So the head needs a loop of its own:
def drop_values(head, unwanted):
# the front is a special case
while head is not None and head.val in unwanted:
head = head.next
node = head
while node is not None and node.next is not None:
if node.next.val in unwanted:
node.next = node.next.next
else:
node = node.next
return head
A dummy head is an extra node in front of the head that holds no value. With it, every real node has a predecessor, and the special case is gone:
def drop_values(head, unwanted):
dummy = Node(None, head)
node = dummy
while node.next is not None:
if node.next.val in unwanted:
# stay put: the new node.next hasn't been checked
node.next = node.next.next
else:
node = node.next
return dummy.next
print(values(drop_values(linked([7, 7, 3, 7, 5]), {7})))
drop_values(7, 7, 3, 7, 5) with unwanted {7}. What's left?
Reverse a list in place
Reversing a list turns every next around. It's the pointer-order rule again, once per node.
Inside the loop, why save after = node.next before setting node.next = prev?
By default, Python stops a recursive reverse near 1,000 nodes, so use a loop
Reversing can be written with recursion too, and in Python that has a limit.
def reverse_recursive(node):
if node is None or node.next is None:
return node
new_head = reverse_recursive(node.next)
node.next.next = node
node.next = None
return new_head
It's correct, and it makes one call per node. Python keeps every unfinished call on its call stack and, by default, stops at a depth of 1,000. Past that it raises RecursionError.
Run from a script, reverse_recursive reversed 999 nodes and raised RecursionError: maximum recursion depth exceeded at 1,000. The loop reversed 1,000,000.
A thousand nodes is a small list. So in Python, a walk over a list is a loop. A recursive walk can always become a loop with a stack you keep yourself, and a list doesn't even need the stack, because each node has only one next node.
In the editor, finish reverse_first(head, k) with a loop. It reverses the first 3 of six nodes.
Two pointers at two speeds
A linked list has no index, but two pointers that move at different speeds can still answer questions about positions in one walk, with O(1) memory.
def middle(head):
slow = fast = head
while fast is not None and fast.next is not None:
slow, fast = slow.next, fast.next.next
return slow
print(middle(linked([1, 2, 3, 4, 5])).val, middle(linked([1, 2, 3, 4, 5, 6])).val)
fast moves two nodes for each one slow moves. Where does slow stop on 1 to 5, and on 1 to 6?
Keep a gap of k, and the trailing pointer stops k from the end
A fixed gap between two pointers finds a position counted from the end.
def kth_from_end(head, k):
lead = head
for _ in range(k):
if lead is None:
# fewer than k nodes
return None
lead = lead.next
trail = head
while lead is not None:
lead, trail = lead.next, trail.next
return trail
nums = linked([1, 2, 3, 4, 5])
print([kth_from_end(nums, k).val for k in (1, 2, 5)], kth_from_end(nums, 6))
On 1 to 5, what are the 1st, 2nd and 5th from the end, and the 6th?
Find a cycle, and the node where it starts
A list that loops is the classic two-speed question. Finding that it loops is the first half. Finding the node where the loop starts is the second.
The seen-set from the hash-maps lesson answers it first: walk, and if a node is already in the set, the list loops.
def has_cycle_set(head):
seen, node = set(), head
while node is not None:
if node in seen:
return True
seen.add(node)
node = node.next
return False
A node in a set is keyed by identity, since Node defines no __eq__ of its own. That's O(n) time and O(n) memory.
Two pointers do it in O(1) memory. This is Floyd's cycle detection, often called the tortoise and the hare:
def has_cycle(head):
slow = fast = head
while fast is not None and fast.next is not None:
slow, fast = slow.next, fast.next.next
if slow is fast:
return True
return False
def looped(n, back_to):
nodes = [Node(v) for v in range(n)]
for a, b in zip(nodes, nodes[1:]):
a.next = b
nodes[-1].next = nodes[back_to]
return nodes[0]
print(has_cycle(looped(8, 3)), has_cycle(linked([1, 2, 3])))
True False
looped(8, 3) makes nodes 0 to 7, and node 7 points back at node 3. Here are the two pointers on it, step by step:
head = looped(8, 3)
slow = fast = head
step = 0
while True:
slow, fast = slow.next, fast.next.next
step += 1
print(f"step {step}: slow on {slow.val}, fast on {fast.val}")
if slow is fast:
break
looped(8, 3): nodes 0 to 7, and 7 points back at 3. slow moves one node a step and fast two. On which node do they meet?
Restart one pointer at the head, step both by one, and they meet where the loop starts
Put one pointer back at the head, leave the other at the meeting point, and move both one step at a time:
node, meet = head, slow
step = 0
print(f"step {step}: from the head on {node.val}, from the meeting point on {meet.val}")
while node is not meet:
node, meet = node.next, meet.next
step += 1
print(f"step {step}: from the head on {node.val}, from the meeting point on {meet.val}")
step 0: from the head on 0, from the meeting point on 5
step 1: from the head on 1, from the meeting point on 6
step 2: from the head on 2, from the meeting point on 7
step 3: from the head on 3, from the meeting point on 3
They meet again on node 3, the start of the loop. To see why, write down where a walk from the head stands: after = 0 to 10 steps, it's on node 0, 1, 2, 3, 4, 5, 6, 7, 3, 4, 5. Here , the steps to the loop, and , the loop's length:
| Walk | Steps | Ends on |
|---|---|---|
| slow | node 5 | |
| fast | node 5 | |
| from the head | node 3, the loop's start | |
| from the meeting point | node 3 |
From t = 3 on, the node repeats every 5 steps, once per lap of the loop. That one fact gives the whole argument.
When they meet, slow has taken some number of steps , and fast has taken . Here .
They stand on the same node, and they can only share a node on the loop. So the extra steps that fast took went around the loop a whole number of times: is a multiple of . Here , one lap.
The meeting point is steps from the head. Walk it more steps and it's steps from the head. That's the start of the loop, steps in, plus whole laps.
The pointer from the head reaches the start after the same steps. Before that, it's still on the part before the loop while the other one is on the loop, so they can't meet sooner. You never need to know : the meeting tells you when you've walked it.
On a short loop, the pointer from the meeting point goes round whole laps first
A common shortcut says the meeting point is nodes short of the loop's start. The start can be closer than that, and then the pointer from the meeting point makes whole laps while the other one walks in. Try a long lead-in and a short loop, nodes 0 to 8 with node 8 pointing back at node 6, so and :
def both_phases(head):
slow = fast = head
i = 0
while True:
slow, fast = slow.next, fast.next.next
i += 1
if slow is fast:
break
node, meet, steps = head, slow, 0
while node is not meet:
node, meet = node.next, meet.next
steps += 1
print(f"meet on node {slow.val} after i = {i} steps")
print(f"then both on node {node.val} after {steps} more steps")
both_phases(looped(9, 6))
looped(9, 6): a lead-in of 6 nodes and a loop of 3. Where do slow and fast meet?
Where two lists meet
Two lists can share their ending. The question is which node they share first, and the trap is in the word node.
shared = Node(7, Node(3, Node(6)))
# 2 -> 9 -> 7 -> 3 -> 6
a = Node(2, Node(9, shared))
# 5 -> 1 -> 9 -> 7 -> 3 -> 6
b = Node(5, Node(1, Node(9, shared)))
print(a.next.val == b.next.next.val, a.next is b.next.next)
True False
Once two lists share a node, they share everything after it, since that node has only one next. So the picture is a Y, never an X:
Green nodes are the same objects in both lists. Each 9 is its own node.
The first shared node is the 7. Not the 9s: a and b each have a 9, but those are two separate nodes that hold equal values. That's what the True False above says.
Compare nodes with is, because equal values can sit on different nodes
The question asks about nodes, and a node is the same node only when it's the same object. In Python that's is: x is y is true only when x and y are one object.
== happens to work on this Node too. A class without its own __eq__ falls back to identity, so == does the same as is.
Comparing .val is the bug. A version that leveled the two lists and compared values returned the 9 from a.
In the editor, write is_shared(a, b): whether two lists that end share a node. It checks the Y, then two lists whose equal values sit on separate nodes.
Level the lengths, then step both pointers together
The set version comes first. Put every node of a in a set, then walk b until a node is in it:
def shared_by_set(a, b):
seen = set()
while a is not None:
seen.add(a)
a = a.next
while b is not None:
if b in seen:
return b
b = b.next
return None
print(shared_by_set(a, b).val)
7
That's O(m + n) time for lists of m and n nodes, and O(m) memory for the set.
To drop the set, look at where the lengths differ. Past the shared node both lists are the same nodes, so the whole difference in length is in the part before it.
Count both lengths, and move the longer list's pointer ahead by the difference. Now both pointers are the same distance from the end. Step both together until they're the same node:
Step 1 puts pa and pb on two 9s: equal values, two nodes, so go on. Step 2 puts them on the same 7: return it.
If the lists never meet, both pointers reach None on the same step, and None is None ends the loop with the right answer. That's O(m + n) time and O(1) memory.
In the editor, finish first_shared(a, b) by leveling the lengths. It finds the first shared node of the two lists, both ways round.
Switch heads, and both pointers walk the same number of steps
Each pointer walks its own list, then the other one. Both have then walked the same number of nodes, so they arrive at the shared node together.
a has 5 nodes and b has 6, and they share the last 3. Each pointer walks its own list, then switches to the other's head. After how many steps do both stand on the shared 7?
Switching heads was the fastest of the three, with no memory
Measured on two lists of 400,000 and 300,000 nodes that share their last 100,000, median of 5 runs:
| Time | Peak memory | |
|---|---|---|
shared_by_set | 19.3 ms | 25,166,040 bytes |
| level the lengths | 21.9 ms | 356 bytes |
shared_by_switching | 14.4 ms | 0 bytes |
On two lists of 300,000 and 200,000 that never meet, the same three took 13.3 ms, 16.4 ms and 12.1 ms.
The two O(1) versions follow next the same number of times: counted on the first pair of lists, 1,200,000 each. Switching heads was faster because each step does less Python work, with no counter to add to and one loop instead of several.
The slow and fast pointers drawn out on a small list, in the video's drawing chapter. Its code starts at 9:22.
A doubly linked list unlinks a node you hold in O(1)
Give each node a second pointer, prev, to the node before it, and a node can leave the list on its own. The price is one more pointer per node, and twice the assignments to keep right.
class DNode:
def __init__(self, key=None):
self.key = key
self.prev = self.next = None
# sentinels: they hold no key and never leave
head, tail = DNode(), DNode()
# the empty list
head.next, tail.prev = tail, head
def insert_after(node, new):
new.prev, new.next = node, node.next
node.next.prev = new
node.next = new
def unlink(node):
node.prev.next = node.next
node.next.prev = node.prev
def forward(limit=100):
out, node = [], head.next
while node is not tail and len(out) < limit:
out.append(node.key)
node = node.next
return out
def backward(limit=100):
out, node = [], tail.prev
while node is not head and len(out) < limit:
out.append(node.key)
node = node.prev
return out[::-1]
for key in "abc":
insert_after(tail.prev, DNode(key))
c = tail.prev
unlink(c)
insert_after(head, c)
print(forward(), backward())
Push a, b and c to the back, then move c to the front. What do forward() and backward() print?
In insert_after, set the old neighbor's prev before you change node.next
The order inside insert_after matters again. Its first line only sets the new node's own pointers. The last two lines change the neighbors, and node.next.prev = new has to come first, while node.next is still the old neighbor. Swap them:
def insert_after_swapped(node, new):
new.prev, new.next = node, node.next
node.next = new
# node.next is new by now, so this sets new.prev
node.next.prev = new
head, tail = DNode(), DNode()
head.next, tail.prev = tail, head
first = DNode("a")
insert_after_swapped(head, first)
print(first.prev is first, tail.prev is head)
for key in "bc":
insert_after_swapped(tail.prev, DNode(key))
print(forward(), backward())
insert_after_swapped sets node.next = new before node.next.prev = new. After inserting a, b and c, what does backward() return?
A dict from key to node makes every move O(1)
The list makes moving a node O(1), but only once you hold the node. A dict from each key to its node is how you get it in O(1): look up the key, then unlink or move the node.
That pair, a dict pointing into a doubly linked list, is the whole LRU cache. It's also what the checkpoint below builds for sign-in sessions. The LeetCode problem Design Authentication Manager has this shape. One GitHub compilation of OpenAI's LeetCode questions tags it as a doubly linked list question (2 sources).
Every session gets the same ttl, and time only goes forward, so the session started or renewed longest ago always expires first: that one sits right after the head, at head.next. live only has to drop from the front.
In the editor, finish renew and live for Sessions. It starts two sessions, renews the first, and counts the live ones at three times.
Each session is dropped once, so live is amortized O(1)
Every call is O(1) except live, which drops each expired session once. A session is started once and dropped once, so n calls cost O(n) in total: amortized O(1) each, meaning O(1) on average over a run of calls.
Expiry order holds only while every session gets one ttl and time never goes back
The whole design leans on two facts: every session gets the same ttl, and now never goes back from one call to the next. Break the second and the order breaks with it.
ttl is 10. start("a", 5), then start("b", 0), with time going back. live(12) drops sessions from the front while they have expired. What does it return?
A worked example: does the list read the same both ways?
The prompt: given the head of a singly linked list, say whether its values read the same forwards and backwards, using O(1) extra memory. 3 -> 1 -> 4 -> 1 -> 3 does. 1 -> 2 -> 3 doesn't.
Clarify. Say out loud that the empty list and a single node count as reading the same. Then ask: can I change the list while I work? Say you will, and that you'll put it back before returning, because callers don't expect a read-only question to rearrange their data.
The obvious answer. Copy the values into a Python list and compare it with its reverse: vals == vals[::-1]. That's O(n) time and O(n) memory. Say it, then say why it doesn't meet the memory limit.
The insight. Reading backwards is what a singly linked list can't do. So reverse the second half in place, compare it with the first half, and reverse it back. That needs three pieces you've built: two speeds to find the middle, the in-place reverse, and pointer care to restore it.
def reads_same_both_ways(head):
if head is None or head.next is None:
return True
# stop slow at the end of the first half
slow = fast = head
while fast.next is not None and fast.next.next is not None:
slow, fast = slow.next, fast.next.next
# reverse the second half in place
second = reverse(slow.next)
a, b, same = head, second, True
while b is not None:
if a.val != b.val:
same = False
break
a, b = a.next, b.next
# put it back
slow.next = reverse(second)
return same
print(reads_same_both_ways(linked([3, 1, 4, 1, 3])), reads_same_both_ways(linked([1, 2, 3])))
True False
On 3, 1, 4, 1, 3, slow stops at the end of the first half. Which node is that?
Every exit goes through the restore
Test every short length, and check the list after each call.
for vals in ([], [4], [5, 5], [1, 2, 2, 1], [1, 2, 3, 2, 1], [1, 2], [1, 2, 3]):
head = linked(vals)
print(vals, reads_same_both_ways(head), values(head) == vals)
[] True True
[4] True True
[5, 5] True True
[1, 2, 2, 1] True True
[1, 2, 3, 2, 1] True True
[1, 2] False True
[1, 2, 3] False True
The last column checks that after every call the list holds its original values in order. That's a test you write for any function that changes its input and promises to put it back.
That's why the loop uses break and not return False. Returning from inside the loop would skip the restore. The caller's list would be left with its second half reversed and cut loose. Every exit goes through slow.next = reverse(second).
The copy is a little faster in Python, and the in-place version saves the memory
One walk to the middle, two reverses of n/2 nodes and one compare: O(n) time and O(1) extra memory.
Measured on a 1,000,000-node list that reads the same both ways, 0 up to 499,999 and back down, median of 5 runs:
- in place: 56.6 ms, with no measurable memory
- the copy: 50.1 ms, with a peak of 16,448,812 bytes
So in Python the copy is a little faster, and it's the right answer at work unless memory is tight. Say that too.
The in-place version has one more catch to name: while it runs, the list is cut short at the middle, so nothing else may read it at the same time.
What if either list may contain a cycle?
One Airbnb candidate reported this version (1 report), and it's the practice problem's last level. Find each list's loop with loop_start first, then sort out five cases:
One list ends in None, and the other loops. Can they share a node?
How do you merge two sorted lists?
Use a dummy head and a tail pointer, then relink the smaller front node each time:
print(values(merge_two(linked([1, 4, 4, 9]), linked([2, 4, 10]))))
merge_two takes from b only when b.val < a.val. Of the three 4s, which come first?
How do you merge k sorted lists?
Merging them into the result one at a time walks the growing result again for every list: O(N k) for N nodes in all.
A heap keeps its smallest item on top, and adding or removing an item in a heap of k items takes O(log k). Python's is the heapq module. A heap of the k front nodes gives O(N log k) in all:
import heapq
def merge_k(heads):
heap = [(head.val, i, head) for i, head in enumerate(heads) if head is not None]
heapq.heapify(heap)
dummy = tail = Node(None)
while heap:
_, i, node = heap[0]
tail.next = node
tail = node
if node.next is not None:
heapq.heapreplace(heap, (node.next.val, i, node.next))
else:
heapq.heappop(heap)
return dummy.next
The list number i sits between the value and the node. So two equal values never fall through to comparing two Node objects, which would raise TypeError.
Merging in pairs, the lists two at a time and then the results two at a time, is also O(N log k):
def merge_one_at_a_time(heads):
out = None
for head in heads:
out = merge_two(out, head)
return out
def merge_in_pairs(heads):
heads = list(heads)
if not heads:
return None
while len(heads) > 1:
heads = [merge_two(heads[i], heads[i + 1] if i + 1 < len(heads) else None)
for i in range(0, len(heads), 2)]
return heads[0]
On sorted lists of random integers, median of 3 runs:
| Lists | Heap | One at a time | In pairs |
|---|---|---|---|
| 10 of 10,000 | 17.4 ms | 23.9 ms | 17.7 ms |
| 100 of 1,000 | 25.5 ms | 207.2 ms | 36.4 ms |
| 1,000 of 100 | 37.0 ms | 2,252.0 ms | 56.1 ms |
What if the list is too long for recursion?
Anything that recurses once per node, reversing, merging, copying, stops near 1,000 nodes in Python. Nothing stops an interviewer from handing you a longer list.
copy.deepcopy copies a linked list by recursing into each node's next. At about how many nodes did it first raise RecursionError?
How do you copy a list whose nodes have an extra pointer?
Each node also has jump, pointing at any node in the list or at None. The copy's jump pointers must point into the copy, not back into the original.
Map each old node to its new one in a dict, the way the hash-maps lesson remembers what it's seen. Then set the pointers in a second pass:
class JNode:
def __init__(self, val, next=None, jump=None):
self.val, self.next, self.jump = val, next, jump
def copy_with_jumps(head):
copies = {None: None}
node = head
while node is not None:
copies[node] = JNode(node.val)
node = node.next
node = head
while node is not None:
copies[node].next = copies[node.next]
copies[node].jump = copies[node.jump]
node = node.next
return copies[head]
The key None: None saves two if statements. copy.deepcopy does this too: its docs say it keeps a memo dictionary of the objects already copied, which is how it copies shared and cyclic references once. Then it recurses.
The follow-up after the dict is to do it in O(1) extra memory. Put each copy right after its original in the list, so old.next is old's copy. Then each copy's jump is old.jump.next. Then split the two lists apart:
def copy_interleaved(head):
node = head
# 1. a copy right after each node
while node is not None:
node.next = JNode(node.val, node.next)
node = node.next.next
node = head
# 2. the copy's jump is the copy of the original's jump
while node is not None:
node.next.jump = node.jump.next if node.jump is not None else None
node = node.next.next
new_head = head.next if head is not None else None
node = head
# 3. split the two lists apart
while node is not None:
twin = node.next
node.next = twin.next
twin.next = twin.next.next if twin.next is not None else None
node = node.next
return new_head
Here it is on three nodes, with A.jump at C and the copies marked with a ':
On 100,000 nodes with random jump pointers, both versions took about 45 ms. The dict version's peak was 14.83 MiB against 8.39 MiB for the copies alone, and the interleaving version's peak was the 8.39 MiB of copies.
On 1,000 nodes both copies checked out against the original, node by node, and the interleaving version left the original's next pointers as they were.
Why do real systems so often prefer an array?
Locality. A CPU reads memory in blocks and keeps recent blocks in its cache, so reading items that sit side by side is cheap. Nodes sit wherever they were allocated, and each next can be a jump to memory that isn't cached.
Here are a million nodes made in order, then linked in a shuffled order:
# the Node above with __slots__
nodes = [SlotNode(v) for v in range(1_000_000)]
order = list(range(1_000_000))
random.Random(0).shuffle(order)
for i in range(len(order) - 1):
nodes[order[i]].next = nodes[order[i + 1]]
A million nodes, linked once in the order they were made and once in a shuffled order. How much slower is the shuffled walk?
What tests would you write?
A walk with a limit, as at the top of this lesson, and a node that counts how often anyone follows next, so the code under test can't loop forever either. The practice problem's tests use the same idea on their hops:
class Budget:
left = 0
class CountingNode:
__slots__ = ("val", "_next")
def __init__(self, val, next=None):
self.val, self._next = val, next
@property
def next(self):
Budget.left -= 1
if Budget.left < 0:
raise AssertionError("followed .next too many times: a walk that never ends")
return self._next
@next.setter
def next(self, node):
self._next = node
@property turns next into a method that runs whenever code reads node.next, and @next.setter runs whenever code assigns it. So every step along the list costs one unit of the budget, and the class needs no other change. Set Budget.left to a few times what a correct walk needs before each call. Then write the cases:
- the empty list, one node and two nodes
- a cycle back to the head, and a node pointing at itself
- two lists with equal values on different nodes
The practice problem, start to finish
That's every piece the practice problem needs. It asks for the three levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.
1.Why is adding a node at the front of a linked list O(1), while
xs.insert(0, x)on a Python list is O(n)?2.To put a new node after
node, which lines keep the rest of the list?3.Nodes 0 to 7 form a list where node 7 points back at node 3. Floyd's slow and fast pointers meet at node 5. How do you find node 3?
4.List a is 2, 9, 7, 3, 6 and list b is 5, 1, 9, 7, 3, 6, where 7, 3, 6 are the same nodes in both. You level the lengths and then step both until the values are equal. What do you get?
5.Why can a doubly linked list unlink a node in O(1) given only that node, while a singly linked list can't?
6.You reverse a 5,000-node list with the short recursive version, one call per node, using Python's default settings. What happens?
Practice
Sources (9)
- Data Structures: Using Lists as Queues · Python 3.12 documentation · Oct 26, 2026
“doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one)”
- collections: deque objects · Python 3.12 documentation · Oct 26, 2026
“Indexed access is O(1) at both ends but slows to O(n) in the middle. For fast random access, use lists instead.”
- Built-in Exceptions: RecursionError · Python 3.12 documentation · Oct 26, 2026
“It is raised when the interpreter detects that the maximum recursion depth (see sys.getrecursionlimit()) is exceeded.”
- Expressions: Identity comparisons · Python 3.12 documentation · Oct 26, 2026
“x is y is true if and only if x and y are the same object”
- Data model: object.__eq__ · Python 3.12 documentation · Oct 26, 2026
“By default, object implements __eq__() by using is”
- dataclasses: Module contents · Python 3.12 documentation · Oct 26, 2026
“If eq is true and frozen is false, __hash__() will be set to None, marking it unhashable (which it is, since it is mutable).”
- Lib/collections/__init__.py at v3.12.16 · CPython source code · Oct 25, 2026
“The circular doubly linked list starts and ends with a sentinel element.”
- copy: Shallow and deep copy operations · Python 3.12 documentation · Oct 26, 2026
“keeping a memo dictionary of objects already copied during the current copying pass”
- Modules/_collectionsmodule.c at v3.12.16 · CPython source code · Oct 25, 2026
“Data for deque objects is stored in a doubly-linked list of fixed length blocks.”