Remove any node in O(1) with prev and next pointers and sentinels, and build an LRU cache from a doubly linked list and a hash map.
You work on the platform behind a mobile app. Your team lead brings four requests:
All of them ask a node to do something to itself or to its neighbours: go back, leave the list, move to the front. With a singly linked list, a node knows only the node after it. To change anything before it you must walk from the head.
The fix is a second pointer in every node. It is called prev, and it points at the node before.
A train has carriages, and each carriage is coupled to the one in front and the one behind. To take a carriage out of the middle, the crew looks at that carriage: it knows both neighbours, joins them to each other, and is free. Nobody walks the whole train from the engine.
In a singly linked train, a carriage knows only the one behind it. To remove carriage seven, someone must first walk from the engine to carriage six.
Carriages with a coupling on both ends: a carriage knows both neighbours, so the crew joins them to each other and the carriage is free.
Each node of a doubly linked list has a value, a next address and a prev address. It costs one more pointer per node, and every change must update both directions. In return, any node can be unlinked from the node itself, and the list can be walked in both directions.
Step by step: A doubly linked list in memory: two addresses in each node. The animated player loads in your browser.
Predict what happens
Q In a singly linked list you hold a pointer to node C, in the middle. Why can you not remove C in constant time?
Answer: B
Removing C means making the node before it point at the node after it. A singly linked node does not know who is before it.
Everything in this lesson is built from two moves. Unlink a node a: the node before it must point forward past it, and the node after it must point back past it.
That is two writes: a.prev.next = a.next and a.next.prev = a.prev.
Link a node new right after a node a: set new.next = a.next and new.prev = a, then set a.next.prev = new and a.next = new. That is four writes, and the order matters.
Read a.next before you overwrite it. If you write a.next = new first, then new.next = a.next reads new itself, and the new node points at itself. In the list 5, 10, 20, inserting 15 after 10 with that order leaves 15 pointing at 15: any walk from 15 never ends.
Step by step: Insert 15 after position 1. The animated player loads in your browser.
With sentinels, there is no special case. The list 5, 10, 20 has a front sentinel before 5 and a back sentinel after 20.
Adding at the front is linking after the front sentinel. Adding at the back is linking after the node before the back sentinel. Removing the first or the last node is the same unlink.
Step by step: Delete the tail, 30. The animated player loads in your browser.
Unlink a node in two writes: the node before it points past it, and the node after it points back past it.
Exercise · Find the bug: The cache drops the newest entry. A list is stored as a table of slots. Slot 0 is the front sentinel, slot 1 is the back sentinel, and links[i] holds [prev, next] for slot i. This function removes the least recently used entry, the one next to the back sentinel, and returns its slot. It returns the wrong slot and loses the rest of the list. Which line is wrong?
def pop_back(links):
last = links[0][1]
before = links[last][0]
links[before][1] = 1
links[1][0] = before
return lastThe same delete on a singly linked list needs a walk to the node before the tail. Compare the hop counts in the two demos.
Step by step: The same delete on a singly linked list. The animated player loads in your browser.
Predict what happens
Q You link a new node after node A. Which write must come first?
Answer: B
If A.next is overwritten first, new.next = A.next reads new itself. The new node points at itself, and the rest of the list is lost from it.
Exercise · Put it in order: Move a node to the front. A list is stored as a table of slots. Slot 0 is the front sentinel, slot 1 is the back sentinel, and links[i] holds [prev, next] for slot i. Arrange the lines into a function that unlinks a real node and links it right after the front sentinel, then returns the table.
def move_to_front(links, node):
prev = links[node][0]
nxt = links[node][1]
links[prev][1] = nxt
links[nxt][0] = prev
first = links[0][1]
links[node][0] = 0
links[node][1] = first
links[first][0] = node
links[0][1] = node
return links
links[first][1] = nodeA browser keeps its pages as a doubly linked list, with a cursor on the current page. Back follows prev, forward follows next, and each stops when there is no node to go to. A visit adds a node after the current one, and it drops every page that was ahead by pointing the current node at the new one.
Start on page 3, visit 8, visit 2, and go back 1 (page 8). Then visit 9, go forward 1 (stays on 9), go back 5 (page 3), and go forward 1 (page 8). The answers are 8, 9, 3, 8. If the visit inserted between the current node and the old next instead of dropping the old pages, the same commands answer [8, 2, 3, 8].
A browser history is a doubly linked list with a cursor: back follows prev, forward follows next, and a visit drops the pages ahead.
Predict what happens
Q The history is 3, 8, 2 and the cursor is on 2. You go back 1 and then visit 9. What does going forward 1 give?
Answer: B
A visit links the new page after the cursor and drops every page that was ahead. After the visit, the history is 3, 8, 9 with the cursor on 9, so forward stays on 9.
A least recently used (LRU) cache holds at most capacity entries. A use of an entry, a read or a write, makes it the most recently used. When a new entry arrives and the cache is full, the entry that was used least recently leaves.
Two structures work together. A hash map from key to node finds an entry in one step. A doubly linked list between two sentinels keeps the entries in order of use: the most recent at the front, the least recent at the back.
A use unlinks the node and links it at the front: six writes. An eviction unlinks the node before the back sentinel and removes its key from the map.
Take a cache of 3 entries and put 1, 2 and 3. The list reads 3, 2, 1. Read key 1, and it moves to the front: 1, 3, 2. Put 4, and the cache is full, so key 2 leaves: the list reads 4, 1, 3, and a read of 2 gives -1.
An LRU cache: a use moves a node to the front, and when the cache is full, the node before the back sentinel is evicted.
Exercise · Predict the output: Which key leaves, and how does the list read?. A cache of 3 keys uses a doubly linked list between two sentinels, newest at the front. The code puts keys 1, 2 and 3, then reads key 2, then evicts the node before the back sentinel. It prints the evicted key, the list from the front, and the list from the back. What does it print?
class Node:
def __init__(self, key):
self.key = key
self.prev = None
self.next = None
front = Node(0)
back = Node(0)
front.next = back
back.prev = front
nodes = [None] * 4
for key in [1, 2, 3]:
n = Node(key)
nodes[key] = n
n.next = front.next
n.prev = front
front.next.prev = n
front.next = n
used = nodes[2]
used.prev.next = used.next
used.next.prev = used.prev
used.next = front.next
used.prev = front
front.next.prev = used
front.next = used
last = back.prev
last.prev.next = last.next
last.next.prev = last.prev
fwd = []
n = front.next
while n is not back:
fwd.append(n.key)
n = n.next
bwd = []
n = back.prev
while n is not front:
bwd.append(n.key)
n = n.prev
print(last.key, "|", *fwd, "|", *bwd)Why both structures? The list alone must search for the key: with 50,000 entries and 10^5 commands, that is about 5 × 10^9 steps. The map alone has no order, so the least recently used entry cannot be found. Each covers the other's gap.
Predict what happens
Q A cache holds 3 entries, put in the order 1, 2, 3. You read key 1, then put key 4. Which key is evicted?
Answer: B
A read counts as a use. After the read the order is 1, 3, 2 from most to least recent, so 2 is at the back and leaves.
Exercise · Break it: Find the input that evicts too early. This least recently used cache takes a capacity (at least 1) and a list of operations. Each row is [kind, key, value]: kind 1 is a put, and kind 0 is a get, which ignores the value. The answer is the result of every get, with -1 for a missing key. Find an input where it gives the wrong answer.
class Node:
def __init__(self, key, val):
self.key = key
self.val = val
self.prev = None
self.next = None
class LruCache:
def __init__(self, capacity):
self.capacity = capacity
self.nodes = {}
self.front = Node(0, 0)
self.back = Node(0, 0)
self.front.next = self.back
self.back.prev = self.front
def unlink(self, n):
n.prev.next = n.next
n.next.prev = n.prev
def link_front(self, n):
n.next = self.front.next
n.prev = self.front
self.front.next.prev = n
self.front.next = n
def get(self, key):
if key not in self.nodes:
return -1
n = self.nodes[key]
self.unlink(n)
self.link_front(n)
return n.val
def put(self, key, val):
if self.capacity < 1:
return
if len(self.nodes) == self.capacity:
last = self.back.prev
self.unlink(last)
del self.nodes[last.key]
if key in self.nodes:
n = self.nodes[key]
n.val = val
self.unlink(n)
self.link_front(n)
else:
n = Node(key, val)
self.nodes[key] = n
self.link_front(n)
def run(capacity, ops):
cache = LruCache(capacity)
out = []
for kind, key, val in ops:
if kind == 1:
cache.put(key, val)
else:
out.append(cache.get(key))
return outA node can have a second pointer to any node in the same structure.
To copy such a chain, make a copy of every node in a first pass and record it in a hash map from original to copy. Then wire the pointers of every copy in a second pass, by looking up the copies of the nodes that the original points at. The two passes matter, because a pointer can lead forward to a node with no copy yet, and a single pass loses it. On the route of the warm-up problem, every forward shortcut of the copy comes back as -1.
A node can also have a child chain.
To flatten the structure, splice each child chain between its parent and the parent's next. Find the last node of the child chain, point it at the old next, and point the parent at the child. Then carry on from the parent's next, which is now the child's head. The walk meets nested children by itself.
A cache can also count uses. The least often used cache keeps one list for each use count, and a variable for the lowest count. It is the same two moves, applied to many lists.
Copy a chain with a second pointer: pass one makes a copy of every node and fills a map, pass two wires the copies through the map.
| Operation | Singly linked | Doubly linked | Doubly linked with a map |
|---|---|---|---|
| Remove a node you hold | O(n): find the node before it | O(1): two writes | O(1) |
| Move a node you hold to the front | O(n) | O(1): two writes to unlink, four to link | O(1) |
| Remove the last node, at the back | O(n) without a prev pointer | O(1) with a back sentinel | O(1) |
| Insert in the middle, after a node you hold | O(1): two writes | O(1): four writes | O(1) |
| Reach a node by index | O(i): one hop per node | O(min(i, n - i)): walk from the nearer end | O(min(i, n - i)) |
| Find a node by key | O(n) | O(n) | O(1) on average |
| LRU get and put | O(n): a search each time | O(n): a search each time | O(1) on average |
| Memory for each node | one pointer | two pointers | two pointers, plus a map entry |
The map finds a node and the pointers change it. Neither is enough alone.
Drive the two-way list yourself and read the hop counter. Use the doubly linked variant for most of it, and switch to the singly linked variant for one comparison.
Try these five, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now build the cache. The lab gives you a Node class with a key, a value, prev and next. It also gives an LruCache class that holds 3 entries, two sentinels and a map from key to node.
You write get, put, remove and size, built on the two moves, unlink and link at the front. The fifth method, to_list, is written for you. It gives the keys from the most to the least recently used.
A get needs a map lookup and a move to the front. A put needs a lookup, then either an update and a move, or a new node and an eviction. A remove needs a lookup and an unlink, and no walk.
Four rules keep the cache correct:
size is the number of keys in the map, and it never passes 3.Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Use a doubly linked list when you hold a node and must remove it, move it or insert next to it in constant time. It also fits when you must walk in both directions. The standard cases are an LRU cache, a browser history, an editor's cursor and a playback queue.
Pair it with a hash map when you must also find nodes by key. In an interview, say that the map finds the node and the list orders it.
If you only walk forward and only change the head, a singly linked list is enough and uses less memory. If order does not matter, a hash map alone is simpler. For a history you can also keep an array and two indexes: back and forward become index changes.
Each node of a doubly linked list costs a second pointer, and every change must keep both directions in step. A mistake in one direction is easy to miss.
a.next = new # first
new.next = a.next # now reads new itselfOn the list 5, 10, 20, inserting 15 after 10 this way makes 15 point at itself, and 20 is unreachable from it. Read the old next into the new node first, then change the neighbours.
a.next = new # forward is right
# new.next.prev = new is missingGoing back from the node after the new one skips the new node. In the playlist problem this gives [15, -1, -1, -1, 10] instead of [15, 15, 20, -1, -1]. Every link and every unlink writes both directions.
evict(node):
unlink(node) # the map still has node.keyThe list is right, but the map still holds the evicted key. A later get finds a node that is no longer in the list, and returns a stale value. The cache also grows past its capacity as seen by the map. Remove the key from the map when you evict or remove a node.
get(key): return map[key].value # no move to the frontEntries that are read all the time are evicted first, because only writes refresh them. On the cache of the warm-up problem this returns [50, 60, -1, 71] instead of [50, -1, -1, 71]. A get must move the node to the front.
The mistake: an eviction unlinks the node but leaves its key in the map, so a later get finds a node that is no longer in the list.
Explain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · Two-way pointers
Q1/3 What does a prev pointer let you do that a singly linked list cannot do in constant time?
Answer: B
Unlinking needs the node before. A prev pointer reaches it in one step, and a singly linked list needs a walk.
Q2/3 How many pointer writes does it take to unlink a node from a doubly linked list with sentinels?
Answer: B
a.prev.next = a.next and a.next.prev = a.prev. Two writes, whatever the length.
Q3/3 What do the two sentinel nodes remove?
Answer: C
Every real node then has a prev and a next, so the same unlink and link code works at the ends.
Checkpoint · Linking and the history
Q1/3 You link a new node after A. Why must you set new.next = A.next before A.next = new?
Answer: B
The old next must be read before it is overwritten.
Q2/3 A browser history is 3, 8, 9 and the current page is 9. You go back 1 and then visit 5. What is the history, and what does forward do?
Answer: B
A visit links the new page after the current page, 8, and drops everything that was ahead. Nothing is ahead of 5.
Q3/3 Why does copying a chain with a second pointer need two passes?
Answer: B
Pass one creates a copy of every node and fills the map. Pass two looks the copies up.
Checkpoint · The LRU cache
Q1/4 Which two structures make an LRU cache run in O(1) for get and put?
Answer: B
The map finds the node, and the list keeps the order and moves nodes with a few pointer writes.
Q2/4 A cache holds 3 entries, put in the order 1, 2, 3. You read key 3, then put key 4. Which key is evicted?
Answer: B
The order after the read is 3, 2, 1 from most to least recent. Key 1 is at the back and leaves.
Q3/4 An eviction unlinks the least recently used node but leaves its key in the map. What goes wrong?
Answer: B
The map must hold exactly the keys that are in the list. Remove the key when you evict.
Q4/4 A get returns the value but does not move the node to the front. What is the effect?
Answer: B
A read is a use. Without the move, the order does not reflect use.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.