CodingNodes / Linked List / LRU Cache System design Space play · ←→ step · R restart

Problem

Build a class LRUCache, a small cache that forgets the entry used least recently when it runs out of room. It has these operations:

  • LRUCache(capacity) creates an empty cache that holds at most capacity entries.
  • get(key) returns the value stored for key, or -1 if there is none. A successful get counts as using that key.
  • put(key, value) stores the pair, replacing the old value if the key exists. Storing a key counts as using it. If that makes the cache hold more than capacity entries, the least recently used one is removed.

get and put must both run in O(1) average time. The input is the list of calls and their arguments; the output lists what each call returns (null for the constructor and for put).

Constraints

  • 1 ≤ capacity ≤ 3000
  • 0 ≤ key ≤ 10⁴, 0 ≤ value ≤ 10⁵
  • At most 2 · 10⁵ calls in total

Examples: pick one to animate

Solutions

TimeO(1) SpaceO(capacity)

Time: The map finds a node in constant time, and unlinking or inserting a node in a doubly linked list rewires a fixed number of pointers.

Space: At most capacity entries are stored, each as one map entry and one list node, plus the two sentinels.

The list keeps entries in order of use: the node after the head is the least recent, the node before the tail the most recent. A hash map from key to node gives instant access, and a node can be unlinked from the middle because it knows both of its neighbours. Every use moves the node to the tail end; eviction removes the node after the head.