Design a Recency-Tracking Key-Value Store
Data Structure DesignAuto-graded · 17 test casesLast updated
Simulate operations on a custom key-value map that efficiently queries the most recently updated active entry.
Design an in-memory key-value container supporting insertion, value retrieval, key deletion, and querying the value of the most recently inserted or modified active key.
Implement a function process_store_operations that takes a sequence of operation names and their corresponding arguments, executes them in order, and returns a list containing the output of each operation.
Supported Operations
-
"add": Takes[key, value].- Inserts the key-value pair if the key does not exist.
- If the key already exists, updates its value and moves it to the most recent position.
- Output:
None.
-
"get": Takes[key].- Returns the stored value associated with
key, orNoneif the key is not present. - Performing a
"get"operation does not change the recency of the key. - Output: The value or
None.
- Returns the stored value associated with
-
"remove": Takes[key].- Deletes the key and its value from the store.
- If the key does not exist, no action is taken.
- Output:
None.
-
"getLast": Takes[].- Returns the value of the most recently added or updated key currently present in the store.
- If the store is empty, returns
None. - Output: The value or
None.
Constraints
operationsis a list of strings where each element is one of"add","get","remove", or"getLast".argumentsis a list of lists matchingoperationsin length and argument format.- Keys are strings or integers, and values are integers.
- All operations should execute efficiently.
Edge Case Rules
- Updating an existing key refreshes its recency so that it becomes the most recent element.
- Removing the current most recent element makes the previously most recent active element the new most recent.
- Removing non-existent keys is a non-op and must not alter the structure or recency tracking.
Examples
Example 1
Input: process_store_operations(['add', 'add', 'get', 'getLast', 'add', 'getLast', 'remove', 'getLast'], [['a', 1], ['b', 2], ['a'], [], ['a', 3], [], ['a'], []])
Output: [None, None, 1, 2, None, 3, None, 2]
Example 2
Input: process_store_operations(['getLast', 'add', 'getLast', 'remove', 'getLast'], [[], ['x', -4], [], ['x'], []])
Output: [None, None, -4, None, None]
Hints
Hint 1
Combining a standard hash table with a doubly linked list allows O(1) lookup as well as O(1) updates to insertion/modification order.
Hint 2
When a key is added or updated, unlink its node if it already exists in the linked list, then append it to the tail (representing the most recent item).
Hint 3
On removal, remove the key from the hash table and unlink its node from the linked list. The new tail automatically becomes the last active element.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To satisfy the requirements of $O(1)$ average time complexity for all four operations (add, get, remove, getLast), we can combine a standard hash map with a doubly linked list:
- Hash Map (
values): Maps each active key directly to its value. This yields $O(1)$ lookup forgetoperations. - Doubly Linked List (
previous&followingpointer maps): Tracks the order of additions/updates.- The tail of the list represents the most recently updated key.
- The head of the list represents the oldest active key.
- When a key is inserted or updated via
add, if it already exists, it is unlinked from its current position in $O(1)$ time and re-appended at the tail. - When a key is deleted via
remove, its node is unlinked in $O(1)$ time, and its entry in the hash map is removed. - Performing
getLastsimply returns the value corresponding to the current tail in $O(1)$ time.
By maintaining node pointers (or link dictionaries mapping key -> prev_key and key -> next_key), we avoid array dynamic reallocations or linear-time searches during deletions.
Correctness & Edge Cases
- Empty Store: When no active keys exist,
tailisNone, andgetLastcorrectly evaluates toNone. - Overwrite Existing Key: Unlinking prior to updating the value ensures the key has only one node in the linked list and resides at the tail.
- Removing Head/Tail: Unlinking updates
headortailpointers correctly when the deleted key sits at either boundary.
Complexity Analysis
- Time Complexity:
add: $O(1)$ average for hash table lookup, insertion, and pointer operations.get: $O(1)$ average hash table read.remove: $O(1)$ average map deletion and linked list splicing.getLast: $O(1)$ constant time tail inspection.- Overall time for $N$ operations is $O(N)$.
- Space Complexity: $O(K)$ auxiliary memory where $K$ is the maximum number of concurrent active keys present in the data structure.
Python Reference Code
from typing import List, Optional
def process_store_operations(operations: List[str], arguments: List[List]) -> List[Optional[int]]:
values = {}
previous = {}
following = {}
head = None
tail = None
results = []
def unlink(key):
nonlocal head, tail
before = previous[key]
after = following[key]
if before is None:
head = after
else:
following[before] = after
if after is None:
tail = before
else:
previous[after] = before
del previous[key]
del following[key]
def append(key):
nonlocal head, tail
previous[key] = tail
following[key] = None
if tail is None:
head = key
else:
following[tail] = key
tail = key
for operation, args in zip(operations, arguments):
if operation == "add":
key, value = args
if key in values:
unlink(key)
values[key] = value
append(key)
results.append(None)
elif operation == "get":
results.append(values.get(args[0]))
elif operation == "remove":
key = args[0]
if key in values:
del values[key]
unlink(key)
results.append(None)
elif operation == "getLast":
results.append(None if tail is None else values[tail])
else:
raise ValueError("unknown operation")
return results