KatInterview

Frequency-Based Cache Eviction

Data Structure DesignAuto-graded · 17 test cases
MediumAuto-gradedData Structure Designhash-mapdoubly-linked-listcache

Last updated

Build a cache that tracks access counts and evicts the least-used item, breaking ties by recency, all in constant time.

Implement a cache with a fixed capacity that evicts entries based on how often they have been accessed. The cache must support two operations, both running in O(1) average time:

  • Retrieve a value by key: If the key exists, return its value and increment its access count. If the key does not exist, return -1.
  • Insert or update a key-value pair: If the key already exists, update its value and increment its access count. If the key is new and the cache is at capacity, remove the entry with the lowest access count. When multiple entries share the lowest count, remove the one that was accessed least recently among them.

Your implementation will be tested by calling a sequence of operations. The first operation initializes the cache with a given capacity. Subsequent operations are retrievals or insertions.

Input format: You will receive two parallel lists:

  • operations: a list of operation names: "LFUCache", "get", or "put"
  • arguments: a list of argument lists, one per operation
    • "LFUCache" receives [capacity]
    • "get" receives [key]
    • "put" receives [key, value]

Output format: Return a list of results, one per operation:

  • "LFUCache" and "put" return None
  • "get" returns the value (an integer) or -1

Constraints

  • 0 ≤ capacity ≤ 10^4
  • 0 ≤ key ≤ 10^5
  • 0 ≤ value ≤ 10^9
  • At most 2 × 10^5 operations in total
  • The first operation is always "LFUCache"

Examples

Example 1

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

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

Hints

Hint 1

Track both the value and the access count for each key using a hash map.

Hint 2

Group keys by their access count. Within each group, maintain insertion order so you can identify the least recently used key.

Hint 3

When a key's access count increases, move it from its current group to the next group. Track the minimum access count across all groups to make eviction fast.