Bounded Cache with Least-Recently-Used Eviction
Data Structure DesignAuto-graded · 14 test casesLast 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 argumentcapacity, 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 argumentskeyandvalue. It insertskeywith the givenvalue, or overwrites the value ifkeyis already stored, and markskeyas the most recently used."get"— takes one argumentkey. Ifkeyis stored, it returns the stored value and markskeyas the most recently used; otherwise it returns-1and 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^5operations[0] == "LRUCache"and every remaining element is"put"or"get"0 <= capacity <= 10^40 <= 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Two operations must both be fast: finding a key by name, and knowing which key was used longest ago. A hash map handles the first. For the second, keep the keys in a doubly linked list ordered from most recently used (just after a dummy head) to least recently used (just before a dummy tail).
Each list node carries its own key. That detail matters: when the oldest node must be evicted, you unlink it from the list and then delete node.key from the map — without the stored key you could not find the map entry.
- Setup: record the capacity and create an empty map plus the two sentinel nodes wired directly to each other.
get(key): look the key up in the map. If absent, report-1and change nothing. Otherwise unlink the node and re-insert it right after the head, then return its value.put(key, value): if the key exists, overwrite the value and move the node to the front — no eviction. If it is new, create a node, register it in the map, push it to the front, and then, if the map now holds more than the capacity, unlink the node before the tail and delete its key from the map. With capacity0, a new key is simply not inserted.
The driver walks the two parallel lists, building the cache at the first operation, and appends None for setup and puts and the integer result for gets.
Why it is correct
Maintain the invariant that the list order exactly matches recency order (front = most recently used) and that the map and the list contain precisely the same set of keys.
Every successful get and every put moves the touched node directly behind the head, so it becomes the most recently used; nothing else changes order, so all other relative positions are preserved. Hence the node just before the tail is always the least recently used entry. Eviction fires only when a new key pushes the size past the capacity, and it removes exactly that tail-adjacent node from both the list and the map, restoring the size limit while keeping the two structures in sync. Misses leave both structures untouched, so recency is unaffected, as required.
Complexity
- Time: O(1) amortized per operation — one hash lookup plus a constant number of pointer rewrites.
- Space: O(capacity) for the map and node pool.