KatInterview

Simulate a Constant-Time LRU Eviction Cache

Data Structure DesignAuto-graded · 19 test cases
EasyAuto-gradedData Structure Designdesign-dslinked-listsarrays

Last updated

Process a series of lookup and insert requests on a fixed-size Least Recently Used (LRU) key-value cache in O(1) time per operation.

Design an in-memory Least Recently Used (LRU) eviction policy cache that maintains fixed capacity and performs both lookups and insertions in expected constant time.

You are given an initial integer capacity, along with two parallel lists: operations containing the sequence of function calls to execute ("get" or "put"), and arguments containing the inputs for each respective operation.

The cache behaves according to the following specifications:

  • get(key): Retrieves the integer value associated with key if present, returning -1 if the key does not exist. Accessing a key marks it as the most recently used entry.
  • put(key, value): Inserts a new key-value pair or updates the existing value of key. Both creating a key and updating an existing key mark the item as the most recently used entry. If inserting a new key causes total entries to exceed capacity, evict the least recently used key prior to completing the request.

Your task is to process all operations in sequential order and return a list of outputs corresponding to each command. For "get", append the returned value (or -1). For "put", append None (represented as null in JSON).

Constraints

  • 1 <= capacity <= 3000
  • 0 <= key <= 10^4
  • 0 <= value <= 10^5
  • operations and arguments have equal length $N$, with $1 \le N \le 2 \times 10^5$.
  • operations[i] is either "get" or "put".
  • arguments[i] is [key] when operations[i] is "get", and [key, value] when operations[i] is "put".

Examples

Example 1

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

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

Example 2

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

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

Hints

Hint 1

To achieve O(1) time complexity for both lookup and eviction reordering, combine a hash map with a doubly linked list.

Hint 2

A hash map provides fast lookup from key to node pointer, while the doubly linked list maintains the precise recency order of items.

Hint 3

Updating an existing key using put() changes its value and moves it to the front of recency order, but does not increase total entry count or cause eviction.