Skip to content

visual walkthrough

LFU Cache

HardHash Map + Frequency BucketsReported at: MicrosoftAmazonGoogle+6

An LRU follow-up with frequency buckets.

Solve on LeetCode

The idea

LFU evicts the key used the fewest times, and on a tie the one used longest ago. So keys are ordered by use count first, then by recency.

Keep one recency list per use count (like an LRU per bucket) and remember the smallest count in use. The victim is always the oldest key in that bucket.

Complexity

approachtimespace
Counts and timestampsO(n) per evictionO(n)
Frequency bucketsO(1) per opO(capacity)

More walkthroughs