LFU Cache
Design a least frequently used (LFU) cache. Implement the LFUCache class:
LFUCache(capacity)creates a cache that holds at mostcapacitykeys.get(key)returns the key's value if it's in the cache, or-1if it isn't.put(key, value)sets the key's value, adding the key if it's new.
Every get or put on a key that's in the cache counts as one use of that key, and a newly added key starts with one use. When the cache is full and a new key arrives, first remove the key with the fewest uses. If several keys tie, remove the one that was used least recently.
Both get and put must run in O(1) average time. The tests run a sequence of operations on one cache and check the value returned by every get, in order.
Example 1
Input: ["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"] [[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]] Output: [1, -1, 3, -1, 3, 4]
After get(1), key 1 has two uses and key 2 has one, so put(3, 3) removes key 2. Keys 1 and 3 then both have two uses after get(3). Key 1 was used less recently, so put(4, 4) removes it.
Example 2
Input: ["LFUCache", "put", "get", "put", "get", "get"] [[1], [1, 10], [1], [2, 20], [1], [2]] Output: [10, -1, 20]
With room for one key, adding key 2 removes key 1 even though key 1 has more uses.
Constraints
1 <= capacity <= 100000 <= key <= 100000and0 <= value <= 10^9- At most
200000calls are made togetandput.
Approach
Finding the key to remove by scanning every key takes O(n) time per eviction. To do it in O(1), the cache needs to know at all times which keys have the fewest uses and, among those, which was used least recently.
Keep three pieces of state. A map from each key to its value and use count. A map from each use count to the keys with that count, kept in order from least to most recently used: an ordered dictionary in Python, a LinkedHashSet in Java, an insertion-ordered Set in JavaScript and a linked list in C++. And min_count, the smallest count that has any keys.
Using a key moves it from its count's group to the end of the next count's group. If that empties the group for min_count, increase min_count by one, since the key is now in that next group. Evicting removes the first key in the min_count group. Adding a new key gives it a count of 1, puts it at the end of group 1 and sets min_count to 1.
Steps
- Store each key's value and use count, a map from count to an ordered group of keys, and
min_count. - In
get, return-1for a missing key. Otherwise, move the key to the next count's group, updatemin_countif its old group emptied, and return the value. - In
putfor an existing key, update the value and move the key the same way. - In
putfor a new key at full capacity, remove the oldest key in themin_countgroup. Then add the new key with a count of 1 and setmin_countto 1.
from collections import OrderedDict, defaultdict
class LFUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.values = {} # key -> value
self.counts = {} # key -> number of uses
self.by_count = defaultdict(OrderedDict) # count -> keys, least recently used first
self.min_count = 0
def _touch(self, key: int) -> None:
# move key from its current count group to the next one
count = self.counts[key]
del self.by_count[count][key]
if not self.by_count[count]:
del self.by_count[count]
if self.min_count == count:
self.min_count += 1
self.counts[key] = count + 1
self.by_count[count + 1][key] = None
def get(self, key: int) -> int:
if key not in self.values:
return -1
self._touch(key)
return self.values[key]
def put(self, key: int, value: int) -> None:
if key in self.values:
self.values[key] = value
self._touch(key)
return
if len(self.values) == self.capacity:
# evict the least recently used key among those with the lowest count
old, _ = self.by_count[self.min_count].popitem(last=False)
if not self.by_count[self.min_count]:
del self.by_count[self.min_count]
del self.values[old]
del self.counts[old]
self.values[key] = value
self.counts[key] = 1
self.by_count[1][key] = None
self.min_count = 1Complexity
- Time:
O(1)average forgetandput. Every step is a hash map operation or an insert or remove at a known position in an ordered group. - Space:
O(capacity)for the maps and groups.
Common mistakes
- Breaking ties by insertion order instead of most recent use. A key that's used moves to the back of its new group.
- Forgetting that
puton an existing key also counts as a use. - Searching for the new minimum count after an eviction. A new key always arrives with a count of 1, so
min_countsimply becomes 1.
1. What is an LFU Cache?
An LFU (Least Frequently Used) cache is a memory management system with a fixed capacity. It tracks how often items are accessed and evicts the least popular items when it runs out of space. It has one critical rule and one tie-breaker rule:
2. The Brute Force Approach (O(N) Time)
In a brute force setup, you prioritize simplicity over speed. You might use a single hash map (dictionary) where the key stores an object containing the
value, itsfrequency, and atimestampof its last access.get(key): O(1) time. You look up the key, return the value, and increment its frequency and update the timestamp.put(key, value): O(N) time. When the cache is full, you have no quick way to know which item has the lowest frequency. You must iterate through every single item in the cache (size N) to find the minimum frequency (and check the timestamps if there is a tie) before deleting it.In a MAANG interview, an O(N) eviction will fail the optimal requirements.
3. The Optimal Approach (O(1) Time)
To achieve O(1) for both
getandput, you must eliminate the need to search for the lowest frequency. You achieve this by grouping items by their frequency so you always know exactly where to look.You need three distinct pieces of state:
4. How the Code Answer Connects to the Optimal Strategy
The Python code provided below perfectly implements the optimal O(1) strategy using built-in data structures:
self.key_to_val_freqacts as the quick lookup (Item 1). It gives you the value and the frequency instantly.self.freq_to_keysacts as the frequency buckets (Item 2). By usingcollections.OrderedDict, it natively acts as a hash map backed by a doubly linked list. This allows O(1) addition, O(1) deletion, and perfectly tracks the LRU order for ties.self.min_freqacts as the minimum frequency tracker (Item 3). When you insert a brand-new item, this resets to1. When the lowest frequency bucket empties out (because you accessed its only item, moving it to a higher bucket), you simply increment this integer byLFU Cache Design (O(1) Time Complexity)
To pass a MAANG-level interview for this question, your LFU (Least Frequently Used) Cache must handle both
getandputoperations in strict O(1) time.The cleanest and most efficient way to implement this in Python during an interview is by combining a standard hash map with a frequency hash map that points to ordered dictionaries (which function natively as doubly linked lists to handle ties).
Core Data Structures
key_to_val_freq: A hash map storingkey -> [value, frequency].freq_to_keys: A hash map storingfrequency -> OrderedDict. TheOrderedDictelegantly handles the LRU (Least Recently Used) tie-breaker policy. When multiple keys have the same frequency, the oldest one is evicted first.min_freq: An integer tracking the lowest frequency currently in the cache to ensure O(1) eviction.Implementation
Python
`import collections class LFUCache: def __init__(self, capacity: int): self.capacity = capacity self.min_freq = 0 # key -> [value, frequency] self.key_to_val_freq = {} # frequency -> OrderedDict(key -> None) self.freq_to_keys = collections.defaultdict(collections.OrderedDict) def get(self, key: int) -> int: if key not in self.key_to_val_freq: return -1 val, freq = self.key_to_val_freq[key] # 1. Remove key from its current frequency list del self.freq_to_keys[freq][key] # 2. If this was the minimum frequency and its list is now empty, increment min_freq if not self.freq_to_keys[freq] and self.min_freq == freq: self.min_freq += 1 # 3. Update the frequency and move key to the new frequency list self.key_to_val_freq[key][1] += 1 self.freq_to_keys[freq + 1][key] = None return val def put(self, key: int, value: int) -> None: if self.capacity <= 0: return # If key exists, update value and reuse get() to bump frequency if key in self.key_to_val_freq: self.key_to_val_freq[key][0] = value self.get(key) return # If at capacity, evict the LFU (and LRU if there's a tie) if len(self.key_to_val_freq) >= self.capacity: # popitem(last=False) removes the first item inserted (LRU) evict_key, _ = self.freq_to_keys[self.min_freq].popitem(last=False) del self.key_to_val_freq[evict_key] # Insert the new key self.key_to_val_freq[key] = [value, 1] self.freq_to_keys[1][key] = None self.min_freq = 1`Why this works:
get: Direct lookup inkey_to_val_freq. Updating the frequency takes O(1) because dictionary deletion and insertion are average O(1).put: If capacity is reached, we checkfreq_to_keys[min_freq]and pop the first item in O(1) time. Managingmin_freqis also O(1) because it only resets to1on a new insertion, or increments by1during agetif a frequency bucket empties out.