LeetCode #460 Hard

LFU Cache

LFU Cache is LeetCode 460 (Hard). Design a least frequently used cache that holds at most capacity keys and supports two calls:

  • get(key): return the key's value, or -1 if it is not in the cache.
  • put(key, value): insert the key or update its value. If a new key arrives while the cache is full, first remove the least frequently used key. If several keys share the lowest use count, remove the one used longest ago.

Every key has a use counter. It is 1 when the key is inserted, and each get or put on the key adds 1. Both calls must run in O(1) average time, over up to 2 × 10⁵ calls.

Constraints
  • 1 <= capacity <= 10⁴
  • 0 <= key <= 10⁵
  • 0 <= value <= 10⁹
  • At most 2 × 10⁵ calls will be made to get and put.
designhash-tablelfu
Open on LeetCode ↗
02

Intuition

Eviction needs two facts at once: the smallest use count, and the oldest key among those with that count. One sorted order cannot give both, so put keys into buckets by use count, and keep each bucket in the order the keys arrived.

  • Bucket: a use count, mapped to its keys, oldest first.
  • Use: a key moves from bucket f to the back of bucket f + 1, so it becomes the newest key with its new count.
  • Smallest count: one number, min_freq. A use can only empty bucket f by moving its key to f + 1, and a new key always starts at 1, so min_freq either goes up by one or resets to 1.
How to spot this pattern

A cache that must evict by one rule and break ties by another, both in O(1), usually needs a hash map for lookup plus one ordered list per value of the first rule.

03

Approach

Try it first

Before reading on, decide what you would scan to find the key to evict, then ask what you could store so that the scan is never needed. Aim for O(1) per call.

1

Keep a key table and count buckets

vals maps each key to [value, count]. buckets maps each count to an OrderedDict of keys, oldest first. An ordered dict, like a doubly linked list with a key-to-node map, removes any key and pops the oldest in O(1).

2

Move a key up on every use

_bump deletes the key from buckets[f], adds it at the end of buckets[f + 1], and stores the new count. Adding at the end makes it the newest key with that count, which is what decides later ties.

3

Raise min_freq when its bucket empties

If buckets[f] is now empty, delete it, and if f was min_freq, set min_freq = f + 1. The key that just moved sits in bucket f + 1, so that bucket is never empty.

4

Treat an update as a use

get on a missing key returns -1; otherwise it bumps the key and returns the value. put on a key already in the cache changes the value and bumps it too, and removes nothing, because the number of keys does not grow.

5

Evict, then insert a new key

If the cache is full, pop the oldest key from buckets[min_freq] and delete it from vals. Then store the new key with count 1 at the end of buckets[1] and set min_freq = 1, since no key can have a smaller count.

04

Code in Python, C++ and Java

▶1from collections import OrderedDict, defaultdict
▶2 
▶3 
▶4class LFUCache:
▶5 def __init__(self, capacity: int):
▶6 self.cap = capacity
▶7 self.vals = {} # key -> [value, count]
▶8 self.buckets = defaultdict(OrderedDict) # count -> keys, oldest first
▶9 self.min_freq = 0
▶10 
▶11 def _bump(self, key):
▶12 f = self.vals[key][1]
▶13 del self.buckets[f][key]
▶14 if not self.buckets[f]:
▶15 del self.buckets[f]
▶16 if self.min_freq == f:
▶17 self.min_freq = f + 1
▶18 self.buckets[f + 1][key] = None
▶19 self.vals[key][1] = f + 1
▶20 
▶21 def get(self, key: int) -> int:
▶22 if key not in self.vals:
▶23 return -1
▶24 self._bump(key)
▶25 return self.vals[key][0]
▶26 
▶27 def put(self, key: int, value: int) -> None:
▶28 if key in self.vals:
▶29 self.vals[key][0] = value
▶30 self._bump(key)
▶31 return
▶32 if len(self.vals) == self.cap:
▶33 old, _ = self.buckets[self.min_freq].popitem(last=False)
▶34 del self.vals[old]
▶35 self.vals[key] = [value, 1]
▶36 self.buckets[1][key] = None
▶37 self.min_freq = 1
callnone yetcapacity 2used 1×emptyused 2×emptyused 3×emptyoldest on topreturned by getempty cache, room for 2 keys
capacity2
min_freq0
Each column is a bucket: the keys used exactly that many times, oldest at the top. The min tag marks the lowest count in use, which is where the next eviction comes from.
callput(1, 1)capacity 2used 1×min1val 1used 2×emptyused 3×emptyoldest on topreturned by getnew key 1 → bottom of used 1×
vals[1]1count 1
min_freq1
A new key has been used once, so it goes to the bottom of bucket 1. No key can have a lower count, so min resets to 1.
callput(2, 2)capacity 2used 1×min1val 12val 2used 2×emptyused 3×emptyoldest on topreturned by getnew key 2 → bottom of used 1×
vals[2]2count 1
min_freq1
A new key has been used once, so it goes to the bottom of bucket 1. min stays at 1.
callget(1)→1capacity 2used 1×min2val 2used 2×1val 1used 3×emptyoldest on topreturned by get1key 1: used 1× → 2×, return 1
get(1)1
min_freq1
A hit is a use, so key 1 moves to the bottom of bucket 2, the newest spot there. The lowest count in use is still 1.
callput(3, 3)capacity 2used 1×min2val 2used 2×1val 1used 3×emptyoldest on topreturned by get1full → evict key 2 from used 1×
min_freq1
evict2
The cache already holds 2 keys, so one must go before key 3 can enter. Bucket 1 holds the least used keys, and key 2 is the only one there.
callput(3, 3)capacity 2used 1×min3val 3used 2×1val 1used 3×emptyoldest on topreturned by get1new key 3 → bottom of used 1×
vals[3]3count 1
min_freq1
A new key has been used once, so it goes to the bottom of bucket 1. min stays at 1.
callget(2)→-1capacity 2used 1×min3val 3used 2×1val 1used 3×emptyoldest on topreturned by get1-1key 2 is not cached → -1
get(2)-1
Key 2 is in no bucket, so it was never added or has been evicted. A miss is not a use, so nothing moves.
callget(3)→3capacity 2used 1×emptyused 2×min1val 13val 3used 3×emptyoldest on topreturned by get1-13key 3: used 1× → 2×, return 3
get(3)3
min_freq2bucket 1 emptied
A hit is a use, so key 3 moves to the bottom of bucket 2, the newest spot there. Bucket 1 is now empty and was the lowest, so min moves up to 2.
callput(4, 4)capacity 2used 1×emptyused 2×min1val 13val 3used 3×emptyoldest on topreturned by get1-13full → evict key 1 from used 2×
min_freq2
evict1
The cache already holds 2 keys, so one must go before key 4 can enter. Bucket 2 holds the least used keys, and key 1 is the oldest of them, so it loses the tie.
callput(4, 4)capacity 2used 1×min4val 4used 2×3val 3used 3×emptyoldest on topreturned by get1-13new key 4 → bottom of used 1×
vals[4]4count 1
min_freq1
A new key has been used once, so it goes to the bottom of bucket 1. No key can have a lower count, so min resets to 1.
callget(1)→-1capacity 2used 1×min4val 4used 2×3val 3used 3×emptyoldest on topreturned by get1-13-1key 1 is not cached → -1
get(1)-1
Key 1 is in no bucket, so it was never added or has been evicted. A miss is not a use, so nothing moves.
callget(3)→3capacity 2used 1×min4val 4used 2×emptyused 3×3val 3oldest on topreturned by get1-13-13key 3: used 2× → 3×, return 3
get(3)3
min_freq1
A hit is a use, so key 3 moves to the bottom of bucket 3, the newest spot there. The lowest count in use is still 1.
callget(4)→4capacity 2used 1×emptyused 2×min4val 4used 3×3val 3oldest on topreturned by get1-13-134key 4: used 1× → 2×, return 4
get(4)4
min_freq2bucket 1 emptied
A hit is a use, so key 4 moves to the bottom of bucket 2, the newest spot there. Bucket 1 is now empty and was the lowest, so min moves up to 2.
callnone yetcapacity 2used 1×emptyused 2×min4val 4used 3×3val 3oldest on topreturned by get1-13-134all calls done → returned 1, -1, 3, -1, 3, 4
returned[1, -1, 3, -1, 3, 4]
Every call took a fixed number of bucket moves, never a scan. The get results, in order, are [1, -1, 3, -1, 3, 4].
05

Common pitfalls

Setting min_freq to 1 before evicting

✗ Wrong
self.min_freq = 1
if len(self.vals) == self.cap:
    old, _ = self.buckets[self.min_freq].popitem(last=False)
✓ Right
if len(self.vals) == self.cap:
    old, _ = self.buckets[self.min_freq].popitem(last=False)
...
self.min_freq = 1

With capacity 1, put(1, 1) then get(1) leaves key 1 alone in bucket 2. put(2, 2) must evict from bucket 2, but resetting first sends it to bucket 1, which is empty, and popitem raises an error.

Updating a value without counting the use

✗ Wrong
if key in self.vals:
    self.vals[key][0] = value
    return
✓ Right
if key in self.vals:
    self.vals[key][0] = value
    self._bump(key)
    return

With capacity 2: put(1, 1), put(2, 2), put(1, 10), put(3, 3). Key 1 has been used twice, so key 2 must go, and get(2) returns -1. Skipping the bump leaves both at count 1, so the older key 1 is evicted instead.

Evicting before checking whether the key exists

✗ Wrong
if len(self.vals) == self.cap:
    evict()
if key in self.vals:
    ...
✓ Right
if key in self.vals:
    ...
    return
if len(self.vals) == self.cap:
    evict()

With capacity 2: put(1, 1), put(2, 2), put(2, 20). The update does not add a key, but the full-cache check fires first and throws key 1 out, so get(1) returns -1 instead of 1.

06

Edge cases

Capacity 1

Every new key evicts the only key, however often it was used: after put(1, 1), get(1), get(1), a put(2, 2) still removes key 1 from bucket 3, and min_freq drops back to 1.

07

Complexity

Time
O(1) per call
Space
O(capacity)
Each call does a fixed number of dictionary and ordered-dictionary steps. vals holds at most capacity keys, and every key sits in exactly one bucket.
08

LFU Cache FAQ

How is LFU different from LRU?

LRU Cache (LeetCode 146) evicts the key unused for the longest time and needs one ordered list; LFU evicts the key used the fewest times and looks at recency only to break ties, so it needs one ordered list per use count.

Can a heap or a TreeMap find the key to evict?

Yes, but not in O(1). A min-heap ordered by (count, last use) or a Java TreeMap from count to keys costs O(log n) per change, and every get changes a count. It passes the time limit, but it misses the O(1) requirement.