KatInterview

Least Recently Used Storage Simulation

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

Last updated

Simulate a fixed-capacity Least Recently Used (LRU) storage engine that processes lookup and insert operations in O(1) time.

Design and simulate a Least Recently Used (LRU) storage engine with a fixed capacity.

The system processes a sequence of queries operating on key-value pairs:

  1. "get": Accepts a key and retrieves its associated value. If the key exists in storage, its access order is updated so it becomes the most recently used item. If the key does not exist, return -1.
  2. "put": Accepts a key and a value.
    • If the key already exists, update its value and mark it as the most recently used item.
    • If the key does not exist and the cache capacity is greater than zero:
      • If the cache has reached maximum capacity, evict the least recently used key before inserting the new key-value pair.
      • Insert the new key-value pair and mark it as the most recently used item.
    • If the capacity is 0, no items can ever be stored, so new keys are ignored.
    • A "put" operation always returns None (represented as null in JSON output).

Write a function simulate_lru_cache that accepts capacity, a list of string operations, and a list of integer parameter lists arguments. Return a list containing the output of each operation in order.

Constraints

  • 0 <= capacity <= 1000
  • 0 <= operations.length <= 10**5
  • arguments.length == operations.length
  • Each operation is either "get" (with arguments[i] containing [key]) or "put" (with arguments[i] containing [key, value]).
  • Keys and values are integers in the range [0, 10**9].

Examples

Example 1

Input: simulate_lru_cache(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: simulate_lru_cache(1, ['put', 'get', 'put', 'get'], [[1, 10], [1], [1, 20], [1]])

Output: [None, 10, None, 20]

Example 3

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

Output: [None, -1]

Hints

Hint 1

To achieve O(1) time complexity for both operations, combine a hash map for key lookups with a doubly linked list for recency ordering.

Hint 2

In Python, `collections.OrderedDict` encapsulates a hash map with a doubly linked list, supporting `.move_to_end(key)` and `.popitem(last=False)`.

Hint 3

Pay close attention to capacity = 0: no items should be stored, and all get operations should return -1.