KatInterview

Process LFU Cache Operations with Frequency and Recency Eviction

Data Structure DesignAuto-graded · 22 test cases
MediumAuto-gradedData Structure Designdesign-dsarrayshash-table

Last updated

Simulate a Least Frequently Used (LFU) cache supporting fast O(1) operations, breaking tie frequencies by least recent usage.

Design and execute a simulation of a Least Frequently Used (LFU) cache of fixed size capacity.

The cache stores integer keys mapped to integer values, along with a use count for each resident key. When inserting a new key into a full cache, the cache must remove the key with the strictly smallest use count. If multiple keys tie for the minimum use count, the key that was least recently used among them is evicted.

You will be given the maximum size capacity, a list of string commands ops, and a matching list of argument lists args. Process the sequence of operations in order and return a list containing the output of all get operations.

Operations Behavior

  1. get(key) (represented by ops[i] = "get" and args[i] = [key]):
    • If key is present in the cache, increment its use count, update its recency to be the most recent, and record its stored value in the output.
    • If key is not present, record -1 in the output. Count remains unchanged.
  2. put(key, value) (represented by ops[i] = "put" and args[i] = [key, value]):
    • If key is already present: overwrite its value with value, increment its use count, and update its recency to be the most recent. No eviction occurs.
    • If key is not present:
      • If the total number of cached keys has reached capacity, evict the key with the minimum use count (breaking ties by evicting the least recently accessed key among those with minimum count).
      • Store the new (key, value) pair with an initial use count of 1. Mark this key as the most recently used.
    • put operations do not produce an output entry.

An evicted key completely forfeits its prior access history. If re-inserted later, its use count resets to 1.

Constraints

  • 1 <= capacity <= 10^4
  • 1 <= len(ops) == len(args) <= 2 * 10^5
  • 0 <= key <= 10^5
  • 0 <= value <= 10^9
  • Each operation should execute in average $O(1)$ time complexity.

Examples

Example 1

Input: simulate_lfu_cache(2, ['put', 'put', 'get', 'put', 'get', 'get', 'put', 'get', 'get', 'get'], [[1, 10], [2, 20], [1], [3, 30], [2], [3], [4, 40], [1], [3], [4]])

Output: [10, -1, 30, -1, 30, 40]

Example 2

Input: simulate_lfu_cache(1, ['put', 'put', 'get', 'put', 'get', 'get'], [[5, 1], [5, 2], [5], [6, 3], [5], [6]])

Output: [2, -1, 3]