Skip to content
BytePatterns

Least Frequently Used Cache

HardHash Tables#design#hash-map#frequency-buckets~45m

Problem

Build a cache that holds at most capacity keys. A get returns the key's value, or -1 if it is missing, and counts as a use; a put inserts a key with one use, or updates an existing key's value and counts as a use. When a new key arrives while the cache is full, first evict the key with the fewest uses, and among those the one whose last use is oldest. Given the capacity and a list of operations, return the results of the get calls, with every operation in O(1) average time.

Examples

Input:  capacity = 2
        ops = put(5, 50), put(6, 60), get(6), get(6), put(7, 70),
              get(5), put(5, 55), get(7), get(5)
Output: [60, 60, -1, -1, 55]
Why:    7 evicts 5 (one use against three); later 5 evicts 7 for the same reason
Input:  capacity = 2
        ops = put(1, 100), put(2, 200), put(1, 111), get(2), put(3, 300),
              get(1), get(3)
Output: [200, -1, 300]
Why:    1 and 2 both have two uses, and 1 was used longer ago, so 1 goes
Input:  capacity = 0
        ops = put(1, 1), get(1)
Output: [-1]
Why:    edge case, a cache with no room keeps nothing

Hints

0 / 3

Stuck on the idea rather than the code? LFU: Frequency Buckets covers it.