Three interview problems that edit a chain in place: remove repeats, splice child chains in, and move cache entries between lists. The move: hold the neighbours before you edit.
You work on a shop catalogue, a search service and a rate cache. The three problems on this street come from them, and none of them may build a new chain. Each edits the existing nodes.
Here is the edit each problem makes, and what you must hold before you make it.
| Problem | The edit | What you hold first |
|---|---|---|
| Remove the repeats in a sorted chain | unlink the next node when it equals the current one | the cursor, whose next you change |
| Expand every group of search results | splice a child chain after its parent | the parent's old next and the child's last node |
| A rate cache that evicts the least often used entry | move a node to the list of the next use count | the node's own previous and next |
Each edit is a handful of link changes. The difficulty is not the edit but knowing which neighbours to hold, so that one change does not cut another.
Exercise · Predict the output: How many nodes are left?. The chain is stored in an array: nxt[i] is the position after node i, and -1 ends the chain. The cursor unlinks the next node while it is equal. How many nodes are left after the edit?
values = [4, 4, 4, 7, 7, 9, 9, 9]
nxt = [1, 2, 3, 4, 5, 6, 7, -1]
curr = 0
while nxt[curr] != -1:
if values[curr] == values[nxt[curr]]:
nxt[curr] = nxt[nxt[curr]]
else:
curr = nxt[curr]
count = 0
node = 0
while node != -1:
count += 1
node = nxt[node]
print(count)An edit in place changes a link of a node you already hold. To remove a node you change the link of the node before it. To splice a chain in you change the link of its parent. To move a node you change the links of both of its neighbours.
Change a link from the node before it, and hold every neighbour you will need before you change anything. Then each edit takes a fixed number of steps and never scans the list.
The three problems differ in how many neighbours they need.
Remove repeats in place: unlink the next node while it equals the cursor, and move on only when it differs.
Exercise · Find the bug: The splice that loops. This splices a child chain between node `at` and its old next, then lists the nodes in order. For one input it lists the child twice and never reaches the rest. Which line is wrong?
def splice(nxt, at, child_head, child_tail):
after = nxt[at]
nxt[at] = child_head
nxt[child_tail] = nxt[at]
order = []
node = 0
while node != -1 and len(order) < len(nxt):
order.append(node)
node = nxt[node]
return orderThe Academy lessons Linked lists, Merge, split and rebuild lists and Doubly linked lists and the LRU cache teach the edits one at a time. This street changes three things.
The edit must stay in place. A chain of 100,000 prices cannot be copied for each fix, so the cursor edits the links it holds. A run of equal prices has any length, so the cursor moves on only when the next price differs. With the prices [1, 1, 1] the right answer is [1], but a cursor that also moves after each unlink returns [1, 1].
The splice needs the last node. To reconnect the old next, you walk the child chain to its end. Each node is visited once across the whole flatten, so the walks add up to the size of the chain. The edit itself is four link changes.
The cache needs one list per count. The LRU cache keeps one list. The least often used cache keeps one list per use count, and a use moves a node to the next list. Scanning for the smallest count would cost a full scan each time.
In a run of 100,000 random accesses over 2,000 keys with a capacity of 1,000, scanning took 49,220,000 steps for 49,220 evictions. Lists need a few link changes for each eviction.
Evicting by recency forgets how often a key was used: the cache must evict the least often used key.
Exercise · Break it: The cache that forgets counts. This counts the hits of a cache that evicts the least often used key, and the oldest one on a tie. It evicts by recency only. Find an input where it gives the wrong count.
def count_hits(capacity, keys):
last = {}
hits = 0
for t, key in enumerate(keys):
if key in last:
hits += 1
elif len(last) == capacity:
victim = min(last, key=lambda k: last[k])
del last[victim]
last[key] = t
return hitsSolve them in this order. The repeats need one cursor, the splice needs three held nodes, and the cache needs a node that holds both neighbours.
Before you code each problem, write the nodes you hold before the first link change. If you cannot list them, you will overwrite a link you still need.
Give each problem about 25 minutes. Spend the first five on a drawing of five nodes with the links as arrows, and cross out an arrow each time you change one.
Test these cases on every rung: an empty chain, a chain of one node, and a chain where the edit touches the last node. Most wrong answers come from a link changed before its old value was saved, or from a cursor that moves too early.
Checkpoint · In-place edits and designs
Q1/5 A cursor removes repeated prices from a sorted chain. After it unlinks a repeat, what should it do?
Answer: B
The new next node may repeat as well, because a run of equal prices has any length. The cursor moves only when the next price differs.
Q2/5 You splice a child chain after a node. Which node must you hold before you change any link?
Answer: A
The child's last node must point at the parent's old next, and once the parent points at the child, only a saved variable still reaches it.
Q3/5 A splice sets nxt[at] = childHead, and then nxt[childTail] = nxt[at]. What goes wrong?
Answer: B
After the first line, nxt[at] holds the child's head, so the child's last node points at its own head. The saved old next must be used instead.
Q4/5 Capacity 3 and the keys 1, 1, 1, 2, 3, 4, 1. Which key does a least often used cache evict when 4 arrives?
Answer: B
Key 1 has three uses. Keys 2 and 3 have one each, and key 2 was used longer ago, so it is evicted and the last access to key 1 is a hit.
Q5/5 Why does a least often used cache keep one list per use count?
Answer: B
The entry to evict is at the oldest end of the smallest count's list, and a use moves a node to the next list with a few link changes. Scanning costs a full scan per eviction.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.