KatInterview

Replay Operations Against an LRU Cache

Data Structure DesignAuto-graded · 19 test cases
MediumAuto-gradedData Structure Designlru-cachehash-mapsimulation

Last updated

Replay a scripted sequence of get/put operations against a fixed-capacity LRU cache and return one result per operation.

You are asked to implement an in-memory cache that holds key/value pairs and discards entries by least-recently-used (LRU) order once it is full.

Instead of building an object with the usual method calls, you will write a single function that replays a scripted list of operations and reports what each one produced.

The function receives:

  • capacity: a positive integer, the maximum number of keys the cache may hold.
  • operations: a list where each entry is the string "get" or "put".
  • arguments: a parallel list of argument lists. An entry paired with "get" is [key]; an entry paired with "put" is [key, value].

For each operation, in order:

  • "get" with [key]: if key is present, return its stored value and treat key as the most recently used. If key is absent, produce -1 and leave the recency order untouched.
  • "put" with [key, value]: insert or replace key with value, and treat key as the most recently used. If this inserts a new key and the number of stored keys now exceeds capacity, remove the least-recently-used key. Replacing the value of an existing key never changes the key count and so never evicts.

Build a result list with exactly one item per operation, in the same order: the produced value (-1 for a miss) for each "get", and None for each "put". Return this list.

Constraints

  • 1 <= capacity <= 1000
  • 1 <= len(operations) == len(arguments) <= 1000
  • Every entry of operations is exactly "get" or "put".
  • "get" entries of arguments have length 1; "put" entries have length 2.
  • 0 <= key <= 10^4
  • -10^4 <= value <= 10^4
  • The returned list has the same length as operations.

Examples

Example 1

Input: simulate_fixed_capacity_cache(2, ['put', 'put', 'get', 'put', 'get', 'get', 'put', 'get'], [[1, 10], [2, 20], [1], [3, 30], [2], [3], [1, 15], [1]])

Output: [None, None, 10, None, -1, 30, None, 15]

Example 2

Input: simulate_fixed_capacity_cache(1, ['get', 'put', 'get', 'put', 'put', 'get'], [[5], [5, 50], [5], [6, 60], [7, 70], [6]])

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

Example 3

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

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

Hints

Hint 1

Record the result of every operation in order; puts contribute None, gets contribute the value or -1.

Hint 2

Track recency with a dict whose insertion order you can reorder: remove and re-insert a key to mark it as freshly used.

Hint 3

Do the eviction check only after inserting a brand-new key, never after an update of an existing one.