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 key is currently cached, increment its access frequency by 1, mark key as the most recently accessed entry, and append its associated value to the output list.
    • When key is absent, append -1 to the output list without modifying any frequencies or recency ordering.
  • put(key, value):
    • When key is already cached, overwrite its stored value with value, increment its access frequency by 1, and mark key as the most recently accessed entry. No entry is evicted.
    • When key is not cached and the cache already holds capacity entries, evict one entry first: choose the cached key with the lowest access frequency, breaking ties by evicting whichever tied key was accessed (get or put) longest ago. Then insert key with value, set its access frequency to 1, and mark it as most recently accessed.
  • 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 in O(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^4
  • 1 <= len(operations) <= 2 * 10^5 and len(arguments) == len(operations)
  • 0 <= key <= 10^5
  • 0 <= value <= 10^9
  • Each operation string is "get" (with [key]) or "put" (with [key, value]).

Step-by-step walkthrough

  1. 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 count 1. Each successful get(key) and each put(key, value) on an already-cached key raises its count by 1 and marks it most recently used.
    • Cache miss on get(key): Appends -1 and 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 per get and put.
  2. 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 at capacity = 10,000 and 200,000 operations, scanning takes up to 2 * 10^9 steps — far too slow. - Maintaining a min-heap of (freq, last_used_step, key) lowers eviction to O(log capacity), which still misses the strict O(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 to 1 or steps upward by +1! Exploiting that +1 transition unlocks O(1) average time.

  3. 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 at f = 1 upon insertion, or stepping from f - 1 to f when accessed), right now is its newest access — so appending it at the back of bucket f keeps every bucket ordered from oldest access at the front to newest access at the back!

    Python's collections.OrderedDict supports all three bucket operations in O(1) average time (combining a hash table with a doubly linked list): - Append key at the back (MRU): bucket[key] = None - Delete key from anywhere in the middle: del bucket[key] - Pop the oldest key from the front (LRU): bucket.popitem(last=False)

  4. How `min_freq` stays accurate in `O(1)` without searching

    To evict in O(1) time, we cannot call min(self.freq_to_keys) (which scans every active bucket). Instead, we track one integer self.min_freq. Notice there are only two events that can change self.min_freq:

    1. An existing key is promoted from old_freq to old_freq + 1:
      • If bucket old_freq still contains other keys, min_freq stays unchanged.
      • Even if bucket old_freq becomes empty, when old_freq > self.min_freq a smaller bucket still exists, so min_freq STILL stays unchanged!
      • Only when old_freq == self.min_freq AND bucket old_freq just became empty does min_freq rise — and the new minimum is guaranteed to be old_freq + 1, because the promoted key now sits in bucket old_freq + 1!
    2. A brand-new key is inserted:
      • Its count is 1, and no positive count is smaller than 1, so self.min_freq = 1 right away! (Even if _evict_lfu() just emptied the previous min_freq bucket, put immediately inserts the incoming key at count 1 and sets self.min_freq = 1, so self.min_freq never stays stale.)
  5. Code the cache state and `_promote`

    We maintain key_to_val, key_to_freq, freq_to_keys, and min_freq, deleting any bucket the moment it empties so memory stays bounded by O(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)
    
  6. Code `_evict_lfu`, `get`, `put`, and trace Example 3

    In _evict_lfu, we pop the front item of self.freq_to_keys[self.min_freq] via popitem(last=False) and delete victim_key from both key_to_val and key_to_freq (discarding its old count). Inside put, always check if key in self.key_to_val: before checking len(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 = 1
    

    Let'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, 60
    
  7. Complete 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 per get and put (meaning hash-table operations take a constant number of steps on average across keys), and O(M) total across the simulation. Each call performs a constant number of dictionary lookups, one OrderedDict deletion (del old_bucket[key]), one OrderedDict insertion (bucket[key] = None), or one front pop (popitem(last=False)), while min_freq updates in O(1) arithmetic without scanning buckets.
  • Space: O(min(C, M)) inside LFUCache (O(C) bounded cache memory), plus O(M) for the returned list of "get" outputs. Every cached key appears once in key_to_val, once in key_to_freq, and in a single OrderedDict bucket, and empty buckets are removed right away so at most C buckets exist simultaneously.

Edge cases

  • capacity == 1: Every put of a new key evicts the lone existing entry even when that entry has accumulated a high frequency (Example 2).
  • Cache miss on get: Returns -1 immediately without creating an entry, bumping any count, or altering min_freq.
  • Updating an existing key in a full cache (put(key, new_val)): Overwrites the value and promotes key to old_freq + 1 without evicting anything.
  • Tie-breaking by latest access rather than initial insertion: If 10 is inserted before 20, then 20 is read and 10 is read afterward, both sit at frequency 2, and 20 is evicted because 10's latest access is newer.
  • Evicted key reinserted later: Because _evict_lfu removes victim_key from key_to_freq, a returning key starts fresh at frequency 1 rather than its old count (Example 3).
  • key == 0 or value == 0: Valid non-negative integers; check if key not in self.key_to_val: rather than if not self.key_to_val.get(key): (which misclassifies value 0 as a miss).
  • Higher bucket empties while min_freq bucket remains occupied: When a hot key steps from frequency 5 to 6 and empties bucket 5 while another key sits at frequency 1, self.min_freq == old_freq is False so min_freq stays 1.

Common mistakes

  • Incrementing min_freq whenever any bucket empties: Only emptying the self.min_freq bucket itself advances min_freq; raising min_freq when a higher bucket empties corrupts min_freq and triggers a KeyError on the next eviction.
  • Checking len == capacity before checking key in self.key_to_val inside put: 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 to O(C) when C keys sit at C distinct frequencies (1, 2, ..., C).
  • Breaking ties by initial insertion order instead of latest access order: Happens when incrementing key_to_freq[key] without moving key to the MRU end of its new bucket.

Alternative approaches

  • Custom Node + DoublyLinkedList per frequency bucket: In languages without a built-in OrderedDict (such as C++ or Go), maintain key -> Node* in one hash map and freq -> DoublyLinkedList in another so detaching a node from freq and appending to freq + 1 uses direct pointer updates in O(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 when O(log M) time and O(M) heap memory are acceptable, though weaker than O(1) time and O(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) mutates key_to_freq, freq_to_keys, and min_freq, a reader-writer lock cannot parallelize hits; the simplest thread-safe baseline guards get and put with one mutex. To scale across many CPU cores, apply lock sharding (partitioning the cache into S independent shards of capacity C // S selected by hash(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,000 and occupy slots indefinitely after demand vanishes, starving newly hot keys that start at 1). 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 + ttl beside key_to_val, and on get(key) treat now >= key_to_expiry[key] as a miss after purging key from all maps and its frequency bucket (note that purging an expired key without inserting a new count-1 key can empty min_freq, so you also maintain a min-heap of active bucket frequencies or advance min_freq lazily). Before evicting a live LFU entry on put, pop any already-expired keys from a min-heap of (expiry_time, key) so expired entries free space first.

Follow-up questions

Similar questions

More Alibaba interview questions

All 3 Alibaba questions →