Python 0460.py
class LFUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.data = defaultdict(int) # (key, value)
self.used = defaultdict(int) # (key, numUsed)
self.freq = defaultdict(list) # (numUsed, (key1, key2, ...)) keys sorted by age
self.least = 0 # min(self.freq)
# internal function: updates LFU counters, key MUST exist
def access(self, key):
# increment usage counter
previous = self.used[key]
current = previous + 1
self.used[key] = current # or += 1
# update self.freq
self.freq[current ].append(key)
self.freq[previous].remove(key)
if not self.freq[previous]: # no item left with old count
self.freq.pop(previous)
# maybe it was the least frequent item
if previous == self.least:
self.least = current # or += 1
def get(self, key: int) -> int:
if key not in self.data:
return -1 # unknown
self.access(key)
return self.data[key]
def put(self, key: int, value: int) -> None:
# overwrite an existing item
if key in self.data:
self.access(key) # update LFU counters
self.data[key] = value
return
# evict an item
if len(self.data) == self.capacity:
# remove this key from all data structures
evict = self.freq[self.least].pop(0)
if not self.freq[self.least]:
self.freq.pop(self.least)
self.used.pop(evict)
self.data.pop(evict)
# now there's at least one slot avaiable for this shiny new item
self.data[key] = value
self.used[key] = 1
self.least = 1
self.freq[1].append(key)
Difficulty
and has an acceptance rate of about 50% (800k+ submissions).
Typical patterns to solve this problem:
- Design
- Doubly Linked List
- Hash Table
- Linked List
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The class implements a Least-Frequently-Used (LFU) cache with a fixed capacity. It stores key-value pairs and tracks how often each key is accessed. When the cache reaches its limit, the entry with the smallest access count (and the oldest among ties) is evicted. The implementation relies on three hash-based containers to achieve constant-time updates and look-ups.
Initialization
The constructor receives the maximum number of entries the cache may hold. Three defaultdict objects are created:
datamaps a key to its stored value.usedmaps a key to the number of times it has been accessed.freqmaps an access count to a list of keys that share that count, preserving insertion order to break ties by age.
A variable least records the smallest access count currently present, allowing quick identification of the eviction candidate.
def __init__(self, capacity: int):
self.capacity = capacity
self.data = defaultdict(int) # key → value
self.used = defaultdict(int) # key → access count
self.freq = defaultdict(list) # count → [keys in age order]
self.least = 0 # current minimum count
Access Update Logic
The internal access method is invoked whenever a key that already exists in the cache is read or overwritten. It increments the key’s usage counter, moves the key from the list belonging to the old count to the list for the new count, and adjusts least when the old count list becomes empty. This keeps the frequency structure synchronized with the actual usage statistics.
def access(self, key):
previous = self.used[key]
current = previous + 1
self.used[key] = current
self.freq[current].append(key)
self.freq[previous].remove(key)
if not self.freq[previous]:
self.freq.pop(previous)
if previous == self.least:
self.least = current
Get Operation
get first checks whether the requested key is present. If it is missing, the method returns -1. When the key exists, access is called to update its usage statistics, and the stored value is returned. This ensures that reads contribute to the LFU ordering.
def get(self, key: int) -> int:
if key not in self.data:
return -1
self.access(key)
return self.data[key]
Put Operation
put handles three distinct situations: overwriting an existing entry, evicting the least-frequently-used entry when the cache is full, and inserting a brand-new entry.
When the key already exists, the method updates its usage count via access and replaces the stored value. No eviction occurs because the entry remains in the cache.
If the cache is at capacity and the key is new, the method evicts the first key from the list associated with least. Because the list preserves age order, the oldest key among those with the minimal count is removed. After eviction, the new key is inserted with an initial usage count of 1, and least is reset to 1.
def put(self, key: int, value: int) -> None:
if key in self.data:
self.access(key)
self.data[key] = value
return
if len(self.data) == self.capacity:
evict = self.freq[self.least].pop(0)
if not self.freq[self.least]:
self.freq.pop(self.least)
self.used.pop(evict)
self.data.pop(evict)
self.data[key] = value
self.used[key] = 1
self.least = 1
self.freq[1].append(key)
Edge Cases Handled
The implementation gracefully deals with a request for a non-existent key by returning -1 without altering internal state. When the cache is empty, least starts at 0 and is updated to 1 upon the first insertion, ensuring that subsequent eviction logic has a valid baseline. During eviction, the code checks whether the list for the current least count becomes empty after removing an entry; if so, the corresponding entry in freq is removed, preventing stale empty lists from lingering. The access method also updates least when the smallest count list disappears, guaranteeing that least always reflects the true minimum usage count.
If the capacity is set to zero, the eviction block will trigger on every insertion attempt, effectively discarding any new entry immediately. The code still maintains correct internal structures because the eviction path removes the placeholder before the new entry is added, leaving the cache empty as intended.
Performance Optimizations
The design leverages hash-based containers (defaultdict) to achieve constant-time look-ups for keys, usage counts, and frequency buckets. By storing keys in lists within each frequency bucket, the implementation can quickly identify the oldest key with the minimal count via pop(0). Maintaining the least variable eliminates the need to scan the frequency map when determining which bucket to evict from, turning eviction into a direct operation. Updating the usage count moves a key between two lists without rebuilding any structures, and the conditional removal of empty frequency buckets keeps the freq map compact, reducing memory overhead. These choices collectively ensure that both read and write paths execute with minimal overhead, suitable for high-throughput caching scenarios.
ELI5 - Simplified Explanation
Imagine you have a small toy box that can only hold a few toys at a time. Because the box is small, you have to be very careful about which toys stay inside. This code acts like a helper who decides which toys get to stay and which ones need to go back on the shelf.
When you want to play with a toy, the helper looks to see if it is already in the box. If it is, the helper notices you played with it one more time. The helper keeps a secret tally of how many times you have played with every toy in the box.
If you bring a new toy to put in the box and there is no room left, the helper looks at the tally. The helper finds the toy that has been played with the least amount of times and takes it out to make space for the new one. This ensures that the toys you use the most are always inside ready for you to grab.
When you ask for a toy, the helper quickly checks if it is hidden in the box. If it is there, the helper does the same magic to show how much you love that toy before giving it to you. If the box gets too full, the helper gently kicks out the toys that nobody wants to play with lately, keeping the favorites right there in the box for the next game.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | Rust | Go | ||||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | begeekmyfriend | C | |||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | TS | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| wisdompeak | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | TypeScript | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| wisdompeak | C++ | ||||||||||
| yuanliu666 | Kotlin |
Videos
Similar Problems
- problem 146: LRU Cache
- problem 588: Design In-Memory File System
Solved On The Same Day
- problem 893: Groups of Special-Equivalent Strings
- problem 2069: Walking Robot Simulation II
- problem 2070: Most Beautiful Item for Each Query
- problem 2498: Frog Jump II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality