KatInterview

Simulate LFU Cache Sequence

Data Structure DesignAuto-graded · 19 test cases
HardAuto-gradedData Structure Designhash-tablelinked-listdesign

Last updated

Process a series of LFU cache queries with LRU tie-breaking and track the output of each operation.

Design and process a sequence of operations on a Least Frequently Used (LFU) cache.

The cache starts empty with a non-negative integer capacity and supports two types of operations:

  1. "get": Takes [key].

    • If key is present in the cache, its frequency count increases by 1, and its access time is updated to be the most recent. Returns the associated value.
    • If key is missing, returns -1. Frequency counts are unaffected.
  2. "put": Takes [key, value].

    • If key already exists, update its associated value to value. Its access frequency increases by 1, and it is marked as the most recently accessed.
    • If key is not present:
      • If the cache has reached maximum capacity, evict the key with the lowest frequency. If multiple keys share the lowest frequency, evict the least recently used (LRU) key among them.
      • Insert the new key with value. Set its initial frequency to 1, and mark it as the most recently accessed key.
    • A "put" operation produces no direct return value (represented as None).

If capacity is 0, no keys can be stored. Any "put" operation is discarded (returns None), and any "get" operation returns -1.

Given capacity, a list of operation names operations, and a list of corresponding parameter arrays arguments, process the operations in order and return a list containing the output of each operation.

Constraints

  • 0 <= capacity <= 10^4
  • 1 <= len(operations) == len(arguments) <= 10^5
  • Each string in operations is either "get" or "put".
  • For "get", arguments[i] has length 1: [key].
  • For "put", arguments[i] has length 2: [key, value].
  • All keys and values are integers in the range [0, 10^9].

Examples

Example 1

Input: lfu_cache(2, ['put', 'put', 'get', 'put', 'get', 'get'], [[1, 1], [2, 2], [1], [3, 3], [2], [3]])

Output: [None, None, 1, None, -1, 3]

Example 2

Input: lfu_cache(2, ['put', 'put', 'put', 'get', 'put', 'get', 'get', 'put', 'get', 'get', 'get'], [[1, 1], [2, 2], [3, 3], [1], [4, 4], [2], [3], [5, 5], [1], [3], [4]])

Output: [None, None, None, -1, None, -1, 3, None, -1, 3, -1]

Example 3

Input: lfu_cache(0, ['put', 'get', 'put', 'get'], [[1, 1], [1], [2, 2], [2]])

Output: [None, -1, None, -1]

Hints

Hint 1

Map each key to both its stored value and its frequency.

Hint 2

Maintain a map from frequency to a doubly-linked list or an OrderedDict of keys to retain recency order for tie-breaking.

Hint 3

Keep track of the minimum frequency currently in the cache (`min_freq`) to achieve O(1) time for evictions.