Simulate a Bounded Recency-Evicting Key-Value Store
Data Structure DesignAuto-graded · 16 test casesLast updated
Replay a batch of get/put commands against a fixed-capacity store that discards its least recently used key on overflow, with O(1) average cost per command.
Bounded Recency Store
A key-value store holds at most capacity entries. Keys and values are integers. When the store grows beyond its capacity, it throws away the entry that was used least recently.
You are given the capacity and a list of commands to run against an initially empty store, in order. Return the result of every command.
Commands
"get"with arguments[key]: ifkeyis in the store, return its value and markkeyas the most recently used. Otherwise return-1and leave the store unchanged."put"with arguments[key, value]: set the value forkey, inserting it if it is absent or overwriting it if it exists. In both caseskeybecomes the most recently used. If the number of entries now exceedscapacity, remove the least recently used entry. Aputalways producesNoneas its result.
"Used" means any get that finds the key, or any put on the key. A get on a missing key does not affect recency.
The check for overflow happens after the insertion or update. Overwriting an existing key never increases the size, so it never causes an eviction.
Input
capacity: a positive integer.operations: a list of strings, each either"get"or"put".arguments: a list of the same length asoperations.arguments[i]is the argument list foroperations[i]:[key]for a get,[key, value]for a put.
Output
A list with one entry per command, in order: the retrieved value (or -1) for each get, and None for each put.
Constraints
capacity >= 1len(operations) == len(arguments)- Keys and values are integers.
- Each command should run in O(1) average time.
Examples
Example 1
Input: run_recency_store(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]
Hints
Hint 1
You need to find a key quickly and also keep track of which key has gone unused the longest. A hash map alone handles the first need but not the second.
Hint 2
Pair a hash map with an ordering of keys from least to most recently used, such as a doubly linked list. Moving a known node to the 'most recent' end must be O(1).
Hint 3
In Python, collections.OrderedDict gives you move_to_end and popitem(last=False). Remember to refresh recency on a put for an existing key, and to evict only after inserting.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Two things must be fast: finding a key, and knowing which key is the least recently used. A hash map gives constant-time lookup. An ordering of the keys by recency gives the eviction candidate. A doubly linked list can move any node to the "most recent" end in O(1) once you have a reference to it, so the map stores key -> node.
Python's OrderedDict is exactly this combination (hash map plus linked list) in the standard library, so the reference solution uses it:
- The front of the
OrderedDictis the least recently used key and the back is the most recently used. get: if the key is missing, output-1. Otherwise callmove_to_end(key)and output the value.put: if the key exists, callmove_to_end(key). Then assign the value. If the size is now abovecapacity, callpopitem(last=False)to drop the front entry. OutputNone.
Why it is correct
Every operation that counts as a use moves the key to the back, so the order from front to back always matches the order from least to most recently used. The front is therefore always the correct eviction victim. Eviction happens only after the insertion, and only when the size exceeds capacity, which matches the rules. An overwrite does not grow the store, so it never evicts. A get miss changes nothing.
Complexity
- Time: O(1) average per command, so O(m) for m commands.
- Space: O(capacity).
Reference solution
from collections import OrderedDict
from typing import List, Optional
def run_recency_store(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
store = OrderedDict()
results = []
for op, args in zip(operations, arguments):
if op == "get":
key = args[0]
if key not in store:
results.append(-1)
else:
store.move_to_end(key)
results.append(store[key])
else: # put
key, value = args
if key in store:
store.move_to_end(key)
store[key] = value
if len(store) > capacity:
store.popitem(last=False)
results.append(None)
return results