← Whiteboard questions

LRU Cache

Design a least-recently-used cache

DSA, Medium, Linked List

Which structure or algorithm, and what does it cost.

Build a fixed-size cache that holds at most capacity entries. get(key) returns the value stored for the key, or -1 if it is missing, and counts as a use of the key. put(key, value) stores or updates the value and counts as a use. When a new key would push the cache over capacity, first drop the entry whose last use is oldest. Each call must take constant time on average.

Examples

Input Capacity 2: put(7,70), put(8,80), get(7)
Output 70
Why Reading key 7 makes it the newest, so the order from oldest to newest is now 8, 7.
Input Capacity 3: put(1,10), put(2,20), put(3,30), get(2), put(4,40), get(1)
Output 20, -1
Why get(2) refreshes key 2, so key 1 is now the oldest. put(4,40) removes key 1, so get(1) finds nothing.
Input Capacity 1: put(5,50), put(5,51), get(5), put(6,60), get(5)
Output 51, -1
Why Edge case: the second put updates key 5 and does not evict it. Storing key 6 then removes key 5.

Constraints

Your answer must contain

Target Aim for O(1) average time for get and put, and O(capacity) memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Two jobs pull against each other: find a key quickly, and know which key was used longest ago. What would you need for each job?

Hint 2 the approach

A hash map finds a key in one step but forgets order. A doubly linked list keeps order and unlinks a node in one step if you hold it.

Hint 3 the key step

Let the map point to list nodes. Newest at the front, oldest at the back. On every use move the node to the front. Evict at the back.

Walkthrough

Full walkthrough brute force to best

Brute force

Keep a list of key and value pairs in order of use. For get and put, scan the list for the key, remove it and add it at the end. When the list is too long, drop the first pair. This is always right, but each call scans up to capacity items. With capacity 100,000 and a million calls that is too slow, and the task asks for O(1) average.

Best method

Combine two structures. A hash map from key to node gives lookup in one step. A doubly linked list ordered by recency, with the newest at the front and the oldest at the back, gives move-to-front and remove-oldest in one step each, because a doubly linked list can unlink a node without a scan. Each node stores its key, so that evicting the back node can also delete its entry from the map. Two sentinel nodes at the ends remove the empty-list special cases. Both get and put move the touched node to the front. An update of an existing key counts as a use and never evicts.

Hand trace

Run the second example, capacity 3. After put(1,10), put(2,20), put(3,30) the list is [3, 2, 1], newest first. get(2) returns 20 and moves 2 to the front: [2, 3, 1]. put(4,40): the cache is full, so evict the back node 1 and delete it from the map; the list is [4, 2, 3]. get(1) finds no key 1 in the map, so it returns -1.

Code

class LRU:
    class N:
        __slots__ = ('k', 'v', 'p', 'n')
        def __init__(s, k=None, v=None): s.k = k; s.v = v; s.p = s.n = None
    def __init__(self, cap):
        self.cap = cap; self.m = {}
        self.h = self.N(); self.t = self.N()     # sentinels
        self.h.n = self.t; self.t.p = self.h
    def _unlink(self, x): x.p.n = x.n; x.n.p = x.p
    def _front(self, x):
        x.n = self.h.n; x.p = self.h; self.h.n.p = x; self.h.n = x
    def get(self, k):
        x = self.m.get(k)
        if x is None: return -1
        self._unlink(x); self._front(x)
        return x.v
    def put(self, k, v):
        if self.cap == 0: return
        x = self.m.get(k)
        if x:                                    # update counts as a use
            x.v = v; self._unlink(x); self._front(x); return
        if len(self.m) == self.cap:              # evict the oldest
            old = self.t.p; self._unlink(old); del self.m[old.k]
        x = self.N(k, v); self.m[k] = x; self._front(x)

Time and memory

O(1) average time for get and put, because each is one map step plus a fixed number of pointer changes. O(capacity) memory for the map and the nodes.

Common mistakes

  • Using a singly linked list. It cannot unlink a node in O(1) without the node before it.
  • Evicting the oldest node but leaving its key in the map. A later get then finds a node that is gone.
  • Not storing the key in the node. Then eviction cannot tell which map entry to delete.
  • Treating put on an existing key as a new entry. It must update the value, count as a use and never evict.

Related problems

More Linked List problems
LRU Cache: hints, walkthrough and Python solution