KatInterview

Bounded Cache with Least-Recently-Used Eviction

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

Last updated

Simulate a capacity-limited key–value cache where lookups and writes both refresh recency and the oldest entry is evicted on overflow.

You are given a scripted sequence of operations that drive a key–value cache with a fixed maximum number of entries. Process the operations in order and report the outcome of every lookup.

The operation names are given as strings in operations, and the matching argument lists are given in arguments, where arguments[i] belongs to operations[i]. The possible operations are:

  • "LRUCache" — takes a single argument capacity, a non-negative integer. It creates the cache and fixes its maximum size. This operation only ever appears as the first operation, and it produces no output.
  • "put" — takes two arguments key and value. It inserts key with the given value, or overwrites the value if key is already stored, and marks key as the most recently used.
  • "get" — takes one argument key. If key is stored, it returns the stored value and marks key as the most recently used; otherwise it returns -1 and the recency order is left unchanged.

When a "put" introduces a new key and the number of stored keys would exceed the capacity, remove the least recently used key first so that the size stays within the limit. Overwriting an existing key never causes an eviction.

Return a list with one entry per operation, in order: None for "LRUCache" and for every "put", and the integer result for every "get".

Note that a capacity of 0 is legal: the cache can never hold anything, so every "put" is effectively discarded and every "get" returns -1.

Constraints:

  • 1 <= len(operations) == len(arguments) <= 2 * 10^5
  • operations[0] == "LRUCache" and every remaining element is "put" or "get"
  • 0 <= capacity <= 10^4
  • 0 <= key, value <= 10^5
  • The returned list has exactly the same length as operations

Examples

Example 1

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

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

Example 2

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

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

Hints

Hint 1

A dictionary alone answers lookups, but it does not tell you which key is oldest — you need a second structure that records recency order.

Hint 2

A doubly linked list with two dummy sentinel ends lets you unlink a node and push it to the front in constant time without special-casing empty lists.

Hint 3

Store the key inside each node, so that when you evict the node just before the tail you can also delete that key from the dictionary.