LFU Cache Simulation with Recency Tie-Breaking
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Design and simulate an in-memory key-value cache bounded by capacity entries using a Least Frequently Used (LFU) eviction policy with Least Recently Used (LRU) tie-breaking.
Implement simulate_lfu_cache, which starts from an empty cache, executes a chronological list of "get" and "put" calls, and collects the return values of all "get" calls:
def simulate_lfu_cache(capacity: int, operations: list[str], arguments: list[list[int]]) -> list[int]:
pass
For each index i, operations[i] is either "get" (paired with arguments[i] = [key]) or "put" (paired with arguments[i] = [key, value]). Each cached entry tracks an integer access frequency according to the following semantics:
get(key):- When
keyis currently cached, increment its access frequency by1, markkeyas the most recently accessed entry, and append its associated value to the output list. - When
keyis absent, append-1to the output list without modifying any frequencies or recency ordering.
- When
put(key, value):- When
keyis already cached, overwrite its stored value withvalue, increment its access frequency by1, and markkeyas the most recently accessed entry. No entry is evicted. - When
keyis not cached and the cache already holdscapacityentries, evict one entry first: choose the cached key with the lowest access frequency, breaking ties by evicting whichever tied key was accessed (getorput) longest ago. Then insertkeywithvalue, set its access frequency to1, and mark it as most recently accessed.
- When
- Eviction resets history: Once a key is evicted, its prior frequency is discarded. Re-inserting that key later starts its frequency fresh at
1. "put"calls produce no output values. Both"get"and"put"must run inO(1)average time per call.
Examples
Example 1
Input:
capacity = 2
operations = ["put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
arguments = [[10, 50], [20, 60], [10], [30, 70], [20], [30], [40, 80], [10], [30], [40]]
Output: [50, -1, 70, -1, 70, 80]
get(10) returns 50 and raises key 10's frequency to 2, so put(30, 70) evicts key 20 (frequency 1). Next, get(30) raises key 30 to frequency 2. When put(40, 80) arrives, keys 10 and 30 tie at frequency 2; key 10 was accessed earlier than key 30, so key 10 is evicted.
Example 2
Input:
capacity = 1
operations = ["put", "put", "get", "put", "get", "get"]
arguments = [[5, 15], [5, 25], [5], [8, 80], [5], [8]]
Output: [25, -1, 80]
put(5, 25) updates key 5 in place without evicting anything and bumps its frequency to 2, after which get(5) returns 25 (frequency 3). Because capacity is 1, inserting the new key 8 evicts key 5 regardless of its high frequency.
Example 3
Input:
capacity = 2
operations = ["put", "get", "get", "put", "get", "get", "put", "put", "put", "get", "get", "get"]
arguments = [[4, 40], [4], [4], [7, 70], [7], [7], [9, 90], [4, 44], [6, 60], [4], [7], [6]]
Output: [40, 40, 70, 70, -1, 70, 60]
Keys 4 and 7 both reach frequency 3, with 4 accessed less recently, so put(9, 90) evicts 4. Next, put(4, 44) evicts 9 (frequency 1) and brings 4 back with a fresh frequency of 1 rather than 3, causing put(6, 60) to evict 4 while 7 (frequency 3) stays cached.
Constraints
1 <= capacity <= 10^41 <= len(operations) <= 2 * 10^5andlen(arguments) == len(operations)0 <= key <= 10^50 <= value <= 10^9- Each operation string is
"get"(with[key]) or"put"(with[key, value]).
Step-by-step walkthrough
Understand the cache rules
We want to simulate a bounded LFU (Least Frequently Used) cache across up to
200,000"get"and"put"calls, returning the output of every"get"call in order:- Access count (
freq): Every newly inserted key starts at count1. Each successfulget(key)and eachput(key, value)on an already-cached key raises its count by1and marks it most recently used. - Cache miss on
get(key): Appends-1and leaves all cache state untouched. - Eviction on
put(key, value)for an absent key when full: Removes the cached key with the lowest count; if multiple keys tie for that lowest count, removes whichever tied key was accessed longest ago (LRU tie-breaker). - Reset after eviction: An evicted key forgets its historical count; inserting it again later starts it back at count
1. - Target speed:
O(1)average time pergetandput.
- Access count (
Why scanning or a min-heap falls short
Suppose we store
[value, freq, last_used_step]per key in a plain dictionary: - Scanning every cached key on each eviction to pick the minimum(freq, last_used_step)is straightforward (and makes a clean brute-force test oracle), yet atcapacity = 10,000and200,000operations, scanning takes up to2 * 10^9steps — far too slow. - Maintaining a min-heap of(freq, last_used_step, key)lowers eviction toO(log capacity), which still misses the strictO(1)average-time target.Why does a general heap pay
O(log capacity)? A heap handles arbitrary priority jumps, whereas here a key's count only ever initializes to1or steps upward by+1! Exploiting that+1transition unlocksO(1)average time.Key idea: frequency buckets ordered by recency
Instead of sorting all keys inside one structure, group keys by their integer count inside
freq_to_keys[freq], where each bucket keeps its keys ordered from least recently used (front) to most recently used (back):key_to_val = {10: 50, 30: 70, 40: 80, 50: 90} key_to_freq = {10: 3, 30: 2, 40: 2, 50: 1} min_freq = 1 ---+ | v freq_to_keys: [freq 1]: front (LRU) --> [ 50 ] <-- back (MRU) <-- next victim is 50! [freq 2]: front (LRU) --> [ 30 -> 40 ] <-- back (MRU) [freq 3]: front (LRU) --> [ 10 ] <-- back (MRU)Why does recency order inside each bucket come automatically? Whenever a key enters bucket
f(either atf = 1upon insertion, or stepping fromf - 1tofwhen accessed), right now is its newest access — so appending it at the back of bucketfkeeps every bucket ordered from oldest access at the front to newest access at the back!Python's
collections.OrderedDictsupports all three bucket operations inO(1)average time (combining a hash table with a doubly linked list): - Appendkeyat the back (MRU):bucket[key] = None- Deletekeyfrom anywhere in the middle:del bucket[key]- Pop the oldest key from the front (LRU):bucket.popitem(last=False)How `min_freq` stays accurate in `O(1)` without searching
To evict in
O(1)time, we cannot callmin(self.freq_to_keys)(which scans every active bucket). Instead, we track one integerself.min_freq. Notice there are only two events that can changeself.min_freq:- An existing key is promoted from
old_freqtoold_freq + 1:- If bucket
old_freqstill contains other keys,min_freqstays unchanged. - Even if bucket
old_freqbecomes empty, whenold_freq > self.min_freqa smaller bucket still exists, somin_freqSTILL stays unchanged! - Only when
old_freq == self.min_freqAND bucketold_freqjust became empty doesmin_freqrise — and the new minimum is guaranteed to beold_freq + 1, because the promoted key now sits in bucketold_freq + 1!
- If bucket
- A brand-new key is inserted:
- Its count is
1, and no positive count is smaller than1, soself.min_freq = 1right away! (Even if_evict_lfu()just emptied the previousmin_freqbucket,putimmediately inserts the incoming key at count1and setsself.min_freq = 1, soself.min_freqnever stays stale.)
- Its count is
- An existing key is promoted from
Code the cache state and `_promote`
We maintain
key_to_val,key_to_freq,freq_to_keys, andmin_freq, deleting any bucket the moment it empties so memory stays bounded byO(capacity).class LFUCache: def __init__(self, capacity: int) -> None: self.capacity = capacity # key_to_val: maps key -> cached integer value, e.g. {1: 100, 2: 200} self.key_to_val: Dict[int, int] = {} # key_to_freq: maps key -> current integer use count (>= 1), e.g. {1: 1, 2: 3} self.key_to_freq: Dict[int, int] = {} # freq_to_keys: maps freq -> OrderedDict of keys ordered from LRU (front) # to MRU (back); values are None because OrderedDict acts as an ordered set. self.freq_to_keys: Dict[int, OrderedDict[int, None]] = {} # min_freq: smallest use count currently present in the cache (valid when non-empty) self.min_freq: int = 0 def _append_to_bucket(self, key: int, freq: int) -> None: """Place key at the most-recently-used (back) end of bucket `freq`.""" if freq not in self.freq_to_keys: self.freq_to_keys[freq] = OrderedDict() self.freq_to_keys[freq][key] = None def _promote(self, key: int) -> None: """Increment key's use count by 1 and move it to the MRU end of its new bucket.""" old_freq = self.key_to_freq[key] old_bucket = self.freq_to_keys[old_freq] del old_bucket[key] # Delete empty buckets so memory stays O(capacity), and advance min_freq ONLY # when the bucket that just emptied was the minimum-frequency bucket itself. if not old_bucket: del self.freq_to_keys[old_freq] if self.min_freq == old_freq: self.min_freq = old_freq + 1 new_freq = old_freq + 1 self.key_to_freq[key] = new_freq self._append_to_bucket(key, new_freq)Code `_evict_lfu`, `get`, `put`, and trace Example 3
In
_evict_lfu, we pop the front item ofself.freq_to_keys[self.min_freq]viapopitem(last=False)and deletevictim_keyfrom bothkey_to_valandkey_to_freq(discarding its old count). Insideput, always checkif key in self.key_to_val:before checkinglen(self.key_to_val) == self.capacity, because updating an existing key in a full cache must never evict a victim!def _evict_lfu(self) -> None: """Evict the least-recently-used key inside the smallest-frequency bucket.""" min_bucket = self.freq_to_keys[self.min_freq] # last=False pops from the front (oldest / least recently used key in this bucket). victim_key, _ = min_bucket.popitem(last=False) if not min_bucket: del self.freq_to_keys[self.min_freq] # Remove from both maps so if victim_key is inserted again later, it restarts at 1. del self.key_to_val[victim_key] del self.key_to_freq[victim_key] def get(self, key: int) -> int: # Cache miss: return -1 without altering any counts or recency order. if key not in self.key_to_val: return -1 self._promote(key) return self.key_to_val[key] def put(self, key: int, value: int) -> None: if self.capacity <= 0: return # Phase 1: Existing key -> update value and promote without evicting anything. if key in self.key_to_val: self.key_to_val[key] = value self._promote(key) return # Phase 2: Brand-new key -> if full, evict one victim before inserting. if len(self.key_to_val) == self.capacity: self._evict_lfu() # Phase 3: Insert new key at count 1; 1 is always the new global minimum count. self.key_to_val[key] = value self.key_to_freq[key] = 1 self._append_to_bucket(key, 1) self.min_freq = 1Let's trace Example 3 (
capacity = 2) to watch bucket promotions, tie-breaking, and count reset on reinsertion:Op Out Buckets after (freq: [LRU ... MRU]) min_freq Why ----------- --- ------------------------------------ -------- ---------------------------------- put(4, 40) - {1: [4]} 1 insert 4 at count 1 get(4) 40 {2: [4]} 2 bucket 1 emptied -> min_freq = 2 get(4) 40 {3: [4]} 3 bucket 2 emptied -> min_freq = 3 put(7, 70) - {1: [7], 3: [4]} 1 insert 7 resets min_freq = 1 get(7) 70 {2: [7], 3: [4]} 2 bucket 1 emptied -> min_freq = 2 get(7) 70 {3: [4, 7]} 3 bucket 2 emptied -> min_freq = 3 put(9, 90) - {1: [9], 3: [7]} 1 tie at freq 3: front is 4 -> evict 4 put(4, 44) - {1: [4], 3: [7]} 1 min_freq=1 -> evict 9; 4 restarts at 1! put(6, 60) - {1: [6], 3: [7]} 1 min_freq=1 -> evict 4 (count 1 < 3) get(4,7,6) returns -1, 70, 60Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import OrderedDict class LFUCache: def __init__(self, capacity: int) -> None: self.capacity = capacity # key_to_val: maps key -> cached integer value, e.g. {1: 100, 2: 200} self.key_to_val: Dict[int, int] = {} # key_to_freq: maps key -> current integer use count (>= 1), e.g. {1: 1, 2: 3} self.key_to_freq: Dict[int, int] = {} # freq_to_keys: maps freq -> OrderedDict of keys ordered from LRU (front) # to MRU (back); values are None because OrderedDict acts as an ordered set. self.freq_to_keys: Dict[int, OrderedDict[int, None]] = {} # min_freq: smallest use count currently present in the cache (valid when non-empty) self.min_freq: int = 0 def _append_to_bucket(self, key: int, freq: int) -> None: """Place key at the most-recently-used (back) end of bucket `freq`.""" if freq not in self.freq_to_keys: self.freq_to_keys[freq] = OrderedDict() self.freq_to_keys[freq][key] = None def _promote(self, key: int) -> None: """Increment key's use count by 1 and move it to the MRU end of its new bucket.""" old_freq = self.key_to_freq[key] old_bucket = self.freq_to_keys[old_freq] del old_bucket[key] # Delete empty buckets so memory stays O(capacity), and advance min_freq ONLY # when the bucket that just emptied was the minimum-frequency bucket itself. if not old_bucket: del self.freq_to_keys[old_freq] if self.min_freq == old_freq: self.min_freq = old_freq + 1 new_freq = old_freq + 1 self.key_to_freq[key] = new_freq self._append_to_bucket(key, new_freq) def _evict_lfu(self) -> None: """Evict the least-recently-used key inside the smallest-frequency bucket.""" min_bucket = self.freq_to_keys[self.min_freq] # last=False pops from the front (oldest / least recently used key in this bucket). victim_key, _ = min_bucket.popitem(last=False) if not min_bucket: del self.freq_to_keys[self.min_freq] # Remove from both maps so if victim_key is inserted again later, it restarts at 1. del self.key_to_val[victim_key] del self.key_to_freq[victim_key] def get(self, key: int) -> int: # Cache miss: return -1 without altering any counts or recency order. if key not in self.key_to_val: return -1 self._promote(key) return self.key_to_val[key] def put(self, key: int, value: int) -> None: if self.capacity <= 0: return # Phase 1: Existing key -> update value and promote without evicting anything. if key in self.key_to_val: self.key_to_val[key] = value self._promote(key) return # Phase 2: Brand-new key -> if full, evict one victim before inserting. if len(self.key_to_val) == self.capacity: self._evict_lfu() # Phase 3: Insert new key at count 1; 1 is always the new global minimum count. self.key_to_val[key] = value self.key_to_freq[key] = 1 self._append_to_bucket(key, 1) self.min_freq = 1 def simulate_lfu_cache( capacity: int, operations: list[str], arguments: list[list[int]] ) -> list[int]: cache = LFUCache(capacity) # read_results: return values from "get" operations in chronological order read_results: list[int] = [] for op, args in zip(operations, arguments): if op == "get": read_results.append(cache.get(args[0])) else: cache.put(args[0], args[1]) return read_results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine organizing library books onto numbered shelves labeled "Used 1 time", "Used 2 times", "Used 3 times", and so on. Whenever someone reads or updates a book, you pull it off its current shelf and slide it onto the rightmost end of the next shelf up; whenever the library is full and a brand-new book arrives, you walk straight to the lowest non-empty shelf (min_freq) and remove its leftmost book. That single layout enforces LFU (Least Frequently Used — evicting the item with the smallest access count) while breaking ties by LRU (Least Recently Used — evicting the item untouched for the longest time), using an OrderedDict (a Python dictionary backed by a hash table plus a doubly linked list so insertion order is preserved while lookup, middle deletion, and front removal all take constant average time) for each shelf!
Why do simpler approaches fall short? Storing (freq, last_used_time) per key in a plain dictionary and scanning all keys during eviction takes O(capacity) time per insert — up to 2 * 10^9 steps when capacity = 10,000 and 200,000 operations arrive. Maintaining a min-heap of (freq, last_used_time, key) is faster (O(log capacity) per call), yet a general heap still misses O(1) average time because it ignores the fact that frequencies only ever step by +1 or reset to 1.
Let's trace Example 1's opening operations on a cache of capacity = 2 to see how freq_to_keys and min_freq interact:
1. put(10, 50) -> insert 10 on shelf 1: {1: [10]}, min_freq = 1
2. put(20, 60) -> insert 20 on shelf 1: {1: [10, 20]}, min_freq = 1 (10 is leftmost/LRU)
3. get(10) -> returns 50; 10 moves from shelf 1 to 2:
shelf 1 still holds [20], so min_freq stays 1!
state: {1: [20], 2: [10]}, min_freq = 1
4. put(30, 70) -> cache is full (size 2 == capacity 2):
evict leftmost of shelf min_freq (1) -> evicts key 20!
insert 30 on shelf 1 -> {1: [30], 2: [10]}, min_freq = 1
Complexity
Let M be len(operations) and C be capacity.
- Time:
O(1)average time pergetandput(meaning hash-table operations take a constant number of steps on average across keys), andO(M)total across the simulation. Each call performs a constant number of dictionary lookups, oneOrderedDictdeletion (del old_bucket[key]), oneOrderedDictinsertion (bucket[key] = None), or one front pop (popitem(last=False)), whilemin_frequpdates inO(1)arithmetic without scanning buckets. - Space:
O(min(C, M))insideLFUCache(O(C)bounded cache memory), plusO(M)for the returned list of"get"outputs. Every cached key appears once inkey_to_val, once inkey_to_freq, and in a singleOrderedDictbucket, and empty buckets are removed right away so at mostCbuckets exist simultaneously.
Edge cases
capacity == 1: Everyputof a new key evicts the lone existing entry even when that entry has accumulated a high frequency (Example 2).- Cache miss on
get: Returns-1immediately without creating an entry, bumping any count, or alteringmin_freq. - Updating an existing key in a full cache (
put(key, new_val)): Overwrites the value and promoteskeytoold_freq + 1without evicting anything. - Tie-breaking by latest access rather than initial insertion: If
10is inserted before20, then20is read and10is read afterward, both sit at frequency2, and20is evicted because10's latest access is newer. - Evicted key reinserted later: Because
_evict_lfuremovesvictim_keyfromkey_to_freq, a returning key starts fresh at frequency1rather than its old count (Example 3). key == 0orvalue == 0: Valid non-negative integers; checkif key not in self.key_to_val:rather thanif not self.key_to_val.get(key):(which misclassifies value0as a miss).- Higher bucket empties while
min_freqbucket remains occupied: When a hot key steps from frequency5to6and empties bucket5while another key sits at frequency1,self.min_freq == old_freqisFalsesomin_freqstays1.
Common mistakes
- Incrementing
min_freqwhenever any bucket empties: Only emptying theself.min_freqbucket itself advancesmin_freq; raisingmin_freqwhen a higher bucket empties corruptsmin_freqand triggers aKeyErroron the next eviction. - Checking
len == capacitybefore checkingkey in self.key_to_valinsideput: Wrongly evicts an entry when the caller is simply updating an already-cached key! - Forgetting
del self.key_to_freq[victim_key]on eviction: Leaks memory over long workloads and resurrects stale counts when evicted keys return. - Recomputing
min(self.freq_to_keys)on eviction: Degrades worst-case eviction toO(C)whenCkeys sit atCdistinct frequencies (1, 2, ..., C). - Breaking ties by initial insertion order instead of latest access order: Happens when incrementing
key_to_freq[key]without movingkeyto the MRU end of its new bucket.
Alternative approaches
- Custom
Node+DoublyLinkedListper frequency bucket: In languages without a built-inOrderedDict(such as C++ or Go), maintainkey -> Node*in one hash map andfreq -> DoublyLinkedListin another so detaching a node fromfreqand appending tofreq + 1uses direct pointer updates inO(1)time. - Min-heap with lazy deletion: Push
(freq, step, key)onto a binary heap on every access and discard stale entries during eviction; simpler to code whenO(log M)time andO(M)heap memory are acceptable, though weaker thanO(1)time andO(C)space.
Follow-up questions
- How would you adapt this cache so multiple threads can execute get and put concurrently with minimal contention? Because even
get(key)mutateskey_to_freq,freq_to_keys, andmin_freq, a reader-writer lock cannot parallelize hits; the simplest thread-safe baseline guardsgetandputwith one mutex. To scale across many CPU cores, apply lock sharding (partitioning the cache intoSindependent shards of capacityC // Sselected byhash(key) % S, each protected by its own mutex) so threads accessing different shards proceed in parallel, trading global LFU eviction for close per-shard LFU. - Why can strict LFU degrade under shifting traffic patterns, and what techniques prevent stale high-frequency keys from lingering forever? Strict LFU suffers from cache pollution (entries that surged in popularity hours ago retain huge counts such as
50,000and occupy slots indefinitely after demand vanishes, starving newly hot keys that start at1). Production systems address this via frequency aging (periodically halving all stored frequencies or counting hits only within a sliding window) or TinyLFU (estimating recent hit rates inside a compact Count-Min Sketch — a small fixed-size matrix of hash counters — and admitting a candidate key on eviction only if its recent estimated frequency exceeds the victim's). - How would you extend the design to support per-entry expiration timestamps (TTL) alongside LFU eviction? Store
key_to_expiry[key] = now + ttlbesidekey_to_val, and onget(key)treatnow >= key_to_expiry[key]as a miss after purgingkeyfrom all maps and its frequency bucket (note that purging an expired key without inserting a new count-1key can emptymin_freq, so you also maintain a min-heap of active bucket frequencies or advancemin_freqlazily). Before evicting a live LFU entry onput, pop any already-expired keys from a min-heap of(expiry_time, key)so expired entries free space first.
Follow-up questions
- How would you adapt this cache so multiple threads can execute get and put concurrently with minimal contention?
- Why can strict LFU degrade under shifting traffic patterns, and what techniques prevent stale high-frequency keys from lingering forever?
- How would you extend the design to support per-entry expiration timestamps (TTL) alongside LFU eviction?
Similar questions
- Justifying Team Scope, Staffing Size, and Hidden System Complexity
- Designing an Idempotent Multi-Threaded Kafka Consumer with Cross-Database Sync
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance