KatInterview

Execute Sequence of LRU Cache Instructions

Data Structure DesignAuto-graded · 19 test cases
MediumAuto-gradedData Structure Designhash-tabledoubly-linked-listdesign

Last updated

Simulate a Least Recently Used (LRU) cache supporting fast lookups, insertions, updates, and capacity evictions across a series of operations.

Construct a simulator for a Least Recently Used (LRU) key-value cache.

The cache has a fixed max capacity and processes a sequence of instruction commands:

  • "get": Accepts [key]. Returns the stored value if the key is present in the cache; otherwise, returns -1. Successfully retrieving a key marks it as the most recently used item.
  • "put": Accepts [key, value]. Inserts or updates the key-value pair.
    • If the key already exists, update its value and promote it to most recently used without changing cache size or triggering eviction.
    • If the key is new, insert it as the most recently used item. If the total number of keys exceeds capacity, purge the least recently used key.
    • If capacity is 0, inserting any key has no effect.
    • Every "put" operation yields None (represented as null in JSON output).

Write a function that takes capacity, a list of operation strings operations, and a corresponding list of argument lists arguments, and returns the output produced by each operation in order.

Constraints

  • $0 \le \text{capacity} \le 10^4$
  • $0 \le \text{len(operations)} = \text{len(arguments)} \le 10^5$
  • Each element in operations is either "get" or "put".
  • Arguments for "get" are single-element lists [key].
  • Arguments for "put" are two-element lists [key, value].
  • Keys and values are integers in the range $[-10^9, 10^9]$.

Examples

Example 1

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

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

Example 2

Input: lru_cache_operations(1, ['get', 'put', 'get', 'put', 'put', 'get', 'get'], [[1], [1, 10], [1], [2, 20], [1, 15], [2], [1]])

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

Example 3

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

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

Hints

Hint 1

Combine a hash table for O(1) key lookups with a doubly linked list to track usage ordering.

Hint 2

Dummy head and tail sentinel nodes simplify insertion and removal at the list boundaries.

Hint 3

Remember that both successful 'get' operations and 'put' updates/inserts must move the accessed item to the head of the linked list.