The Runtime Theory
mediumleetcode#hash-map#doubly-linked-list#eviction

Build an LRU Cache

Combine a hash map and a doubly linked list to support constant-time cache lookup, promotion, insertion, and eviction.

The Runtime Theory Team1 min read
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

incapacity=2; put(1,1); put(2,2); get(1); put(3,3); get(2)

out1, -1

incapacity=1; put(1,1); put(2,2); get(1); get(2)

out-1, 2

Implement get(key) and put(key, value) for a least-recently-used cache. A successful get and every put make that key the most recently used. When capacity is exceeded, evict the least recently used key.

Use a hash map from keys to list nodes and a doubly linked list ordered from least to most recently used. Define sentinel nodes or explicit head/tail cases, and write one helper that unlinks and one that inserts a node. The target is O(1) expected time per operation.

Test updating an existing key, reading the current least-recent item, capacity one, and repeated eviction. Explain why a hash map alone cannot identify the least-recent item efficiently.

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.

Not started

Sign in to save your learning progress.

Sign in to save