Skip to content
BytePatterns

Least Recently Used Cache

MediumLinked Lists#doubly-linked-list#hash-map#sentinel-nodes~35m

Problem

Build a fixed-size cache for an API gateway. LRUCache(capacity) creates it; get(key) returns the stored value, or -1 if the key is missing; put(key, value) inserts or updates a key. Both calls count as a use of the key. When a put would push the cache past its capacity, first evict the key that was used longest ago. Both operations must run in O(1) time, and the capacity is between 1 and 3,000. Build the ordering yourself with a doubly linked list instead of using OrderedDict.

Examples

Input:  capacity = 2
        put(1, 1), put(2, 2), get(1), put(3, 3), get(2), put(4, 4), get(1), get(3), get(4)
Output: [1, -1, -1, 3, 4]
Why:    put(3, 3) evicts 2 because get(1) just used 1; put(4, 4) then evicts 1
Input:  capacity = 2
        put(1, 1), put(2, 2), put(1, 10), put(3, 3), get(1), get(2)
Output: [10, -1]
Why:    updating key 1 also counts as a use, so key 2 is the one evicted
Input:  capacity = 1
        put(1, 1), put(2, 2), get(1), get(2)
Output: [-1, 2]
Why:    edge case, every new key evicts the only one stored

Hints

0 / 3

Stuck on the idea rather than the code? Doubly Linked Lists covers it.