Replay Commands on a Fixed-Bucket Key-Value Store
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a hand-built key-value store with a fixed bucket count by replaying a command log, handling collisions and overwrites correctly without a built-in dictionary.
Replay a Key-Value Store Command Log
You are building a small key-value store from scratch and must replay a log of commands against it. The store uses a fixed number of buckets, and several different keys may end up in the same bucket. Your store must stay correct when that happens.
Write a function that takes two parallel lists, commands and payloads. The command at position i is paired with the argument list at position i in payloads. Process the commands in order and return one result per command.
Commands
"HashTable"or"init": payload is[bucket_count]. Creates a new, empty store with that many buckets. The result for this command isNone."put": payload is[key, value]. Storesvalueunderkey. Ifkeyis already present, its old value is replaced, so each key appears at most once. The result isNone."get": payload is[key]. The result is the value currently stored underkey, or-1if the key was never stored.
Rules
- Keys are never null. They may be integers or strings, and both kinds can appear in the same log.
- Two keys are the same only if they are equal. Keys that land in the same bucket must not overwrite or hide each other.
- If
bucket_countis less than 1, treat it as 1. - Bucket selection should come from the key's hash reduced modulo the number of buckets. The result must be a valid, non-negative index.
- You must not use a built-in dictionary, set, or other built-in hash map to hold the entries. Lists are fine.
- Average
putandgetcost should be O(1) when keys are spread reasonably across buckets. - The first command in every log creates the store.
Output
Return a list with exactly one entry per command, in the same order as the input. Entries for creation and put commands are None. Entries for get commands are the stored value, or -1 if the key is absent.
Constraints
commandsandpayloadshave the same length.- Each
getorputhappens after the store has been created. - Keys are non-null integers or strings.
- Values can be any JSON-like value (for example integers or strings).
- No built-in hash map or dictionary may be used for storage.
Examples
Example 1
Input: replay_store_commands(['HashTable', 'put', 'put', 'get', 'get'], [[3], ['a', 10], ['b', 20], ['a'], ['c']])
Output: [None, None, None, 10, -1]
Example 2
Input: replay_store_commands(['HashTable', 'put', 'put', 'get'], [[2], [1, 'first'], [1, 'second'], [1]])
Output: [None, None, None, 'second']
Example 3
Input: replay_store_commands(['HashTable', 'put', 'put', 'get', 'get'], [[4], [0, 'zero'], [4, 'four'], [0], [4]])
Output: [None, None, None, 'zero', 'four']
Hints
Hint 1
Keep a list of buckets, where each bucket is a list of [key, value] pairs. Choose a bucket with hash(key) % number_of_buckets.
Hint 2
Before adding a new pair in put, scan the chosen bucket for an equal key. If found, update its value in place instead of appending a duplicate.
Hint 3
For get, scan only the one bucket and compare keys with equality. Return -1 if the scan ends without a match. Do not forget to clamp the bucket count to at least 1.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use separate chaining. Create a list of bucket_count buckets (at least 1), where each bucket is a list of mutable [key, value] pairs.
For every command:
- Create: build the empty buckets and record
None. - put: compute
index = hash(key) % len(buckets). Scan that bucket for an entry whose key equals the given key. If one exists, overwrite its value in place. Otherwise append a new[key, value]pair. RecordNone. - get: compute the same index and scan that bucket. Return the value of the entry with an equal key, or
-1if there is none.
Why it is correct
- Determinism: a key always hashes to the same bucket, so
getlooks exactly whereputstored it. - Uniqueness:
putsearches before appending, so a key never appears twice and the latest value always wins. - Collision safety: colliding keys sit side by side in one bucket, and the equality check ensures
getreturns the value of the exact key requested. - Absent keys: a key that was never stored is not in its bucket, so the scan ends and
-1is returned. - Index validity: Python's
%with a positive divisor gives a non-negative result, even for negative hashes, and clamping the bucket count to at least 1 prevents modulo by zero.
Complexity
Let n be the number of stored keys and m the number of buckets.
- Creation: O(m).
putandget: O(1 + n/m) on average, which is O(1) when keys are spread evenly. The worst case is O(n) if all keys collide.- Space: O(m + n).
A production table would also resize when the load factor n/m grows too large, which makes operations amortized O(1). That is not needed here because the bucket count is fixed by the creation command.
Reference solution
from typing import List
def replay_store_commands(commands: List[str], payloads: List[List]) -> List:
buckets = None
result = []
for command, args in zip(commands, payloads):
if command in ("HashTable", "init"):
bucket_count = max(1, args[0])
buckets = [[] for _ in range(bucket_count)]
result.append(None)
elif command == "put":
key, value = args
index = hash(key) % len(buckets)
bucket = buckets[index]
found = False
for entry in bucket:
if entry[0] == key:
entry[1] = value
found = True
break
if not found:
bucket.append([key, value])
result.append(None)
elif command == "get":
key = args[0]
index = hash(key) % len(buckets)
value = -1
for entry in buckets[index]:
if entry[0] == key:
value = entry[1]
break
result.append(value)
return result