Doubly linked lists, circular lists and an LRU cache
A doubly linked list gives each node a prev as well as a next, so a node can unlink itself in O(1); joined with a dict it makes an LRU cache whose get and put are both O(1).
Browsers, databases and CDNs all have a kind of cache that holds at most 3 entries (or 30,000) and, when full, throws out the one least recently used: an LRU cache. Both get and put must be O(1). A dict finds a key in one step but does not know which one was used longest ago; keep the order in a list, and every "it was just used, move it to the front" is O(n). The answer is to join a dict and a doubly linked list: the dict finds the node in one step, and the doubly linked list unlinks it and puts it at the front in one step. The last lesson showed that in a singly linked list, holding a node is not enough to delete it, because the node before it cannot be found; a doubly linked node remembers the node before it.
A doubly linked list: one more reference, prev
A doubly linked node has two references: prev points at the node before, next at the node after. Holding node b, deleting it just means making its two neighbours point at each other: b.prev.next = b.next and b.next.prev = b.prev. Press play and watch the arrows on both sides:
b↓1b.prev.next = b.next2b.next.prev = b.prev
In real code, put a sentinel node at each end (the two-ended version of last lesson's dummy node): head and tail hold no data, and the real nodes all sit between them. Then every real node has a node before and a node after, and inserting and deleting never need to check for None.
1class DNode:2 def __init__(self, key=None):3 self.key = key4 self.prev = None5 self.next = None6 7class DList:8 def __init__(self):9 self.head = DNode() # two sentinels: real nodes all sit between them10 self.tail = DNode()11 self.head.next = self.tail12 self.tail.prev = self.head13 14 def push_front(self, node):15 node.prev = self.head # first the new node's own two16 node.next = self.head.next17 self.head.next.prev = node # then the neighbours: the prev of the one after first18 self.head.next = node19 20 def remove(self, node):21 node.prev.next = node.next22 node.next.prev = node.prev23 24 def forward(self):25 out, cur = [], self.head.next26 while cur is not self.tail:27 out.append(cur.key)28 cur = cur.next29 return out30 31 def backward(self):32 out, cur = [], self.tail.prev33 while cur is not self.head:34 out.append(cur.key)35 cur = cur.prev36 return out37 38L = DList()39nodes = {}40for k in "abcd":41 nodes[k] = DNode(k)42 L.push_front(nodes[k])43print(L.forward(), L.backward())44L.remove(nodes["b"]) # holding the node is enough to delete it: O(1)45print(L.forward())46L.remove(nodes["a"])47L.push_front(nodes["a"]) # move to the front: unlink, then put back48print(L.forward())
['d', 'c', 'b', 'a'] ['a', 'b', 'c', 'd'] ['d', 'c', 'a'] ['a', 'd', 'c']
The order of push_front's four lines matters too: if self.head.next = node came first, the next line's self.head.next.prev would be node.prev, and the old first node's prev would never be updated. Just as with a singly linked list: link up the new node first, and change the reference to the old node last.
In a doubly linked list you hold node b. How long does it take to find the node before it?
b.prev gets there in one step: O(1). A singly linked list has no prev, so you walk from the start again, O(n), which is why a singly linked list cannot delete a node given only the node.After deleting b while holding it, what does this print?
1class DNode:2 def __init__(self, val=None):3 self.val = val4 self.prev = None5 self.next = None6 7a, b, c = DNode(1), DNode(2), DNode(3)8a.next, b.prev, b.next, c.prev = b, a, c, b9b.prev.next = b.next10b.next.prev = b.prev11print(a.next.val, c.prev.val)
b.prev.next = b.next makes a point forward straight at c; b.next.prev = b.prev makes c point back straight at a. Both directions skip b: it prints 3 1. Change only one direction and walking backwards still runs into the deleted b.Put the four lines of push_front in order so walking forwards and backwards both come out right: [3, 2, 1] [1, 2, 3].
node.prev = self.headself.head.next.prev = nodenode.next = self.head.nextself.head.next = node
[3, 2, 1] [1, 2, 3]
self.head.next is still the old first node), then the old first node’s prev, and only at the end self.head.next. Move self.head.next = node earlier and every later self.head.next is node itself, so the old first node is lost.A circular list: the tail points back to the head
Point the last node's next back at the first and you have a circular list: there is no None, and from any node you can go all the way round and come back. The classic use is the Josephus problem: n people stand in a circle, counting starts at 1, whoever is counted k is out, counting starts again from the next person, and who is left at the end?
prev↓1prev = tail2while prev.next is not prev:3 for _ in range(k - 1):4 prev = prev.next5 out.append(prev.next.val)6 prev.next = prev.next.next7print(out, prev.val)
Walking a circular list cannot wait for None (it never comes); wait until you are "back at the node you started from":
1class Node:2 def __init__(self, val, next=None):3 self.val = val4 self.next = next5 6def make_circle(n):7 head = Node(1)8 tail = head9 for v in range(2, n + 1):10 tail.next = Node(v)11 tail = tail.next12 tail.next = head # end to end13 return head, tail14 15def show(head):16 out, cur = [], head17 while True:18 out.append(cur.val)19 cur = cur.next20 if cur is head: # back where we started21 break22 return out23 24def josephus(n, k):25 head, tail = make_circle(n)26 out = []27 prev = tail28 while prev.next is not prev:29 for _ in range(k - 1):30 prev = prev.next31 out.append(prev.next.val)32 prev.next = prev.next.next33 return out, prev.val34 35print(show(make_circle(5)[0]))36print(josephus(5, 3))37print(josephus(7, 3))
[1, 2, 3, 4, 5] ([3, 1, 5, 2], 4) ([3, 6, 2, 7, 5, 1], 4)
| singly linked | doubly linked | circular | |
|---|---|---|---|
| Each node | val, next | val, prev, next | as singly linked, the tail pointing back to the head |
| Holding node x, delete it | O(n): find the one before first | O(1): it is x.prev | O(n): go round to find the one before |
| Can it walk backwards? | no | yes | no, but it comes back round |
| Walking stops at | cur is None | cur is tail (the sentinel) | cur is head (back at the start) |
A circular list: 3 → 7 → 9 → back to 3. Counting nodes like this, what does it print?
1class Node:2 def __init__(self, val, next=None):3 self.val = val4 self.next = next5 6c = Node(9)7b = Node(7, c)8a = Node(3, b)9c.next = a10head = a11cur = head12n = 013while cur is not head:14 n += 115 cur = cur.next16print(n)
while checks first: cur is not head is false straight away, so the loop never runs and it prints 0. Python has no do … while; to go round once either use while True, step first and then ask "back at head?", or start from head.next with the count at 1.A circular singly linked list only keeps its last node, tail. Which node is the first?
tail.next. Keeping only tail gives you both ends in one step: that is why you keep the tail, and adding at the front or the back is O(1).6 people stand in a circle. Counting starts at 1, whoever is counted 2 is out, and counting starts again from the next person. Who is left at the end?
How many in the circle
✓Finish count_circle(head): count the nodes of a circular list. You cannot wait for None; wait until you are back at head. For an empty list (head is None) return 0.
5 1 0
1class Node:2 def __init__(self, val, next=None):3 self.val = val4 self.next = next5 6def count_circle(head):7 # start at head and walk until you are back at head8 return 09 10a = Node(1, Node(2, Node(3, Node(4, Node(5)))))11a.next.next.next.next.next = a12b = Node(9)13b.next = b14print(count_circle(a), count_circle(b), count_circle(None))
An LRU cache: a dict plus a doubly linked list
Each of the two does one job:
- The dict: key → node, found in one step.
- The doubly linked list: ordered from most recently used to least. When
getorputuses a key, its node is unlinked and put at the front; when full, the last one (tail.prev) is deleted.
The node must store its key: when the list's last node is deleted, its key is how you delete the matching key from the dict.
1class DNode:2 def __init__(self, key=None, val=None):3 self.key = key4 self.val = val5 self.prev = None6 self.next = None7 8class LRUCache:9 def __init__(self, capacity):10 self.capacity = capacity11 self.map = {} # key -> node12 self.head = DNode() # the front: most recently used13 self.tail = DNode() # the back: least recently used14 self.head.next = self.tail15 self.tail.prev = self.head16 17 def _remove(self, node):18 node.prev.next = node.next19 node.next.prev = node.prev20 21 def _push_front(self, node):22 node.prev = self.head23 node.next = self.head.next24 self.head.next.prev = node25 self.head.next = node26 27 def get(self, key):28 if key not in self.map:29 return -130 node = self.map[key]31 self._remove(node) # just used: move to the front32 self._push_front(node)33 return node.val34 35 def put(self, key, val):36 if key in self.map:37 self._remove(self.map[key])38 elif len(self.map) == self.capacity:39 old = self.tail.prev # the least recently used40 self._remove(old)41 del self.map[old.key]42 node = DNode(key, val)43 self.map[key] = node44 self._push_front(node)45 46c = LRUCache(2)47c.put(1, 1)48c.put(2, 2)49out = [c.get(1)]50c.put(3, 3) # full: 2 was used longest ago, so it goes51out.append(c.get(2))52c.put(4, 4) # full: 1 was used longest ago, so it goes53out += [c.get(1), c.get(3), c.get(4)]54print(out)
[1, -1, -1, 3, 4]
In interviews: the LRU cache (LeetCode 146) comes up all the time, and the interviewer often says "don't use OrderedDict", meaning: write a dict plus a doubly linked list with two sentinels, as above. The complexity to state: get and put are both O(1), space O(capacity). The Josephus problem (LeetCode 1823) can be simulated with a circular list in O(nk).
Why does a node in the LRU cache’s list keep the key as well as val?
tail.prev. The dict maps key → node, and without the key you cannot write del self.map[...], so the dict would keep a node that is no longer in the list. Finding a node is the dict’s job; the list is never searched by key.An LRU cache holds 3. You use 1 2 3 1 4 in that order. Which one is evicted when 4 goes in?
Write the LRU's get and put
✓_remove and _push_front are written already. Finish get and put: a key that is used moves to the front; when adding a new key to a full cache, first delete tail.prev (and remember to delete it from the dict too).
A ['a', 'c', 'b'] -1 ['d', 'a', 'c'] C2 ['c', 'd', 'a']
1class DNode:2 def __init__(self, key=None, val=None):3 self.key = key4 self.val = val5 self.prev = None6 self.next = None7 8class LRUCache:9 def __init__(self, capacity):10 self.capacity = capacity11 self.map = {}12 self.head = DNode()13 self.tail = DNode()14 self.head.next = self.tail15 self.tail.prev = self.head16 17 def _remove(self, node):18 node.prev.next = node.next19 node.next.prev = node.prev20 21 def _push_front(self, node):22 node.prev = self.head23 node.next = self.head.next24 self.head.next.prev = node25 self.head.next = node26 27 def get(self, key):28 # missing: -1; present: move to the front and return val29 return -130 31 def put(self, key, val):32 # already there: unlink the old node first; full: delete tail.prev; then put the new node at the front33 pass34 35 def keys(self):36 out, cur = [], self.head.next37 while cur is not self.tail:38 out.append(cur.key)39 cur = cur.next40 return out41 42c = LRUCache(3)43for k in "abc":44 c.put(k, k.upper())45print(c.get("a"), c.keys())46c.put("d", "D")47print(c.get("b"), c.keys())48c.put("c", "C2")49print(c.get("c"), c.keys())
How you write it at work
At work you do not build it yourself. In CPython, collections.OrderedDict is a dict plus a doubly linked list; move_to_end(key) moves a key to the end and popitem(last=False) deletes the first one, both O(1). An LRU in a dozen lines:
1from collections import OrderedDict2 3class LRUCache:4 def __init__(self, capacity):5 self.capacity = capacity6 self.data = OrderedDict()7 8 def get(self, key):9 if key not in self.data:10 return -111 self.data.move_to_end(key) # just used: move to the end (the newest end)12 return self.data[key]13 14 def put(self, key, val):15 self.data[key] = val16 self.data.move_to_end(key)17 if len(self.data) > self.capacity:18 self.data.popitem(last=False) # delete the first (least recently used)19 20c = LRUCache(2)21c.put(1, 1)22c.put(2, 2)23out = [c.get(1)]24c.put(3, 3)25out.append(c.get(2))26c.put(4, 4)27out += [c.get(1), c.get(3), c.get(4)]28print(out)29print(list(c.data))
[1, -1, -1, 3, 4] [3, 4]
Note the direction is the opposite of the hand-written one: in the OrderedDict the end is the newest and the front is the one used longest ago.
An LRU holding at most 3 uses a b c a d b in turn. What does it print at the end?
1from collections import OrderedDict2 3cache = OrderedDict()4for key in ["a", "b", "c", "a", "d", "b"]:5 if key in cache:6 cache.move_to_end(key)7 else:8 cache[key] = True9 if len(cache) > 3:10 cache.popitem(last=False)11print(list(cache))
[a, b, c]; using a again moves it to the end: [b, c, a]; adding d is one too many, so the first, b, goes: [c, a, d]; adding b is one too many again, so c goes: [a, d, b]. b was deleted once, and comes back as a newly added key.When what you want to cache is a function's results (arguments already worked out are not worked out again), use functools.lru_cache directly:
1from functools import lru_cache2 3calls = 04 5@lru_cache(maxsize=2)6def slow_square(x):7 global calls8 calls += 19 return x * x10 11for x in [1, 2, 1, 3, 1, 2]:12 slow_square(x)13print("really computed", calls, "times")14print(slow_square.cache_info())
really computed 4 times CacheInfo(hits=2, misses=4, maxsize=2, currsize=2)
OrderedDict: for when you control "what counts as used" and "what to delete" yourself; it takes more memory than a plain dict, for the extra linked list.@lru_cache(maxsize=128): adds a cache to a function. The arguments must be hashable (a list will not do, a tuple will);maxsize=Nonemeans no limit (that isfunctools.cache), and remember it keeps holding that memory.- A plain dict also remembers insertion order since 3.7, but it has no
move_to_end; to move a key you mustpopit and put it back.
@lru_cache is on def f(nums). Can you call it with a list?
TypeError: unhashable type. Turn it into a tuple, f(tuple(nums)), and it works.Summary
A doubly linked node can unlink itself in O(1); LRU = dict + doubly linked list
- A doubly linked node adds prev: holding a node is enough to delete it in O(1)
- A sentinel at each end means no None checks; to insert, link up the new node first, change the old reference last
- A circular list's tail points back to the head: walking stops when you are back at the start
- LRU: the dict finds the node, the list keeps the order; move a used one to the front, delete the last when full
- Ready-made: OrderedDict's move_to_end and popitem(last=False), and @lru_cache
1node.prev.next = node.next # unlink node2node.next.prev = node.prev3d.move_to_end(key) # OrderedDict: make it the newest4d.popitem(last=False) # delete the least recently used5@lru_cache(maxsize=128)