KatInterview

Simulate Least-Recently-Used Cache Operations

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

Last updated

Tests your ability to implement a data structure that maintains access order and performs lookups, updates, and evictions efficiently.

You are given a sequence of cache operations to replay against a fixed-size cache that evicts entries using a least-recently-used (LRU) policy.

Write a function that accepts:

  • capacity: the maximum number of key-value pairs the cache can hold (may be zero or negative)
  • operations: a list of operation names, each either "get" or "put"
  • arguments: a list of argument lists; arguments[i] corresponds to operations[i]
    • For "get", the argument list contains one integer [key]
    • For "put", the argument list contains two integers [key, value]

Return a list of results, one per operation:

  • "get" returns the stored value if the key exists in the cache, otherwise -1
  • "put" returns None

Cache behavior:

  • Both "get" (when the key is found) and "put" mark the key as most recently used
  • When inserting a new key into a full cache, remove the least recently used entry first
  • Updating an existing key (a "put" where the key is already present) does not trigger eviction
  • A cache with capacity ≤ 0 can hold nothing; all "get" operations return -1 and all "put" operations are ignored
  • If an operation name is not "get" or "put", raise a ValueError

Constraints

  • capacity may be zero, negative, or positive
  • 1 ≤ len(operations) ≤ 10⁵
  • len(operations) == len(arguments)
  • 1 ≤ key, value ≤ 10⁶
  • Each operation is "get" or "put" (the function should raise ValueError for any other string)

Examples

Example 1

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

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

Example 2

Input: simulate_lru_cache(1, ['put', 'put', 'get', 'put', 'get'], [[1, 10], [1, 20], [1], [2, 30], [1]])

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

Example 3

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

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

Hints

Hint 1

A hash map gives O(1) lookup by key, but how do you track which entry was used least recently?

Hint 2

A doubly linked list allows O(1) removal from the middle and O(1) append to the end; combine it with a hash map from keys to nodes.

Hint 3

Python's OrderedDict is a hash map with an embedded doubly linked list; move_to_end and popitem(last=False) do exactly what you need.