KatInterview

Build a Fixed-Size Cache That Forgets the Least-Used Entry

Data Structure DesignAuto-graded · 21 test cases
MediumAuto-gradedData Structure Designhash-maplinked-listcache

Last updated

Tests your ability to combine a hash map and an ordered structure to implement O(1) reads and writes with recency-based eviction.

Problem

You need to implement a fixed-capacity cache that evicts the entry touched least recently whenever it runs out of room.

The cache supports two operations:

  • fetch(key) — Return the stored value for key, or -1 if it is not in the cache. A successful fetch counts as a use of that key.
  • store(key, value) — Write value for key. If key is already in the cache, update its value and refresh its recency. If the cache is already full and key is new, drop the least recently used entry first, then insert the new one.

Both operations must run in O(1) average time.


How Your Solution Is Evaluated

Your class is driven by a single function that receives:

  • capacity — the maximum number of entries the cache may hold at once.
  • operations — a list of strings, each either "get" or "put".
  • arguments — a parallel list of argument lists:
    • For "get", the inner list holds one integer: [key].
    • For "put", the inner list holds two integers: [key, value].

The function must return a list with one element per operation:

  • For each "get", the element is the integer result (-1 if the key is absent).
  • For each "put", the element is None.

Operations are applied in order, and each one may affect the outcome of later ones.


Constraints

  • 1 ≤ capacity ≤ 1000
  • 0 ≤ key, value ≤ 10^4
  • 1 ≤ len(operations) ≤ 10^4
  • Every "get" entry in operations has exactly one integer in the corresponding arguments entry.
  • Every "put" entry in operations has exactly two integers in the corresponding arguments entry.
  • The value 0 is a valid cached value; do not confuse it with a missing key.

Examples

Example 1

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

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

Hints

Hint 1

You need O(1) lookup by key and O(1) identification of the least-recently-used entry at the same time — think about which two data structures, combined, give you both properties at once.

Hint 2

A doubly linked list maintains order cheaply: moving a node to the front costs a fixed number of pointer rewrites, with no shifting. Pair it with a hash map from key to node and you have both O(1) access and O(1) order updates.

Hint 3

Add a dummy sentinel node at each end of the list so you never have to handle empty-list or single-node edge cases. The node just before the tail sentinel is always the eviction target. Crucially, store the key inside each node so you can remove the map entry when you evict.