Design a Custom Key-Value Map
Data Structure DesignAuto-graded · 15 test casesLast updated
Execute a series of map operations (put, get, remove) by simulating a hash map without using built-in dictionaries or sets.
Design and simulate a custom key-value store class from scratch without using any standard language map, dictionary, or set data structures.
The underlying implementation must handle collision resolution and dynamic resizing. The operations to process are given as two synchronized lists: operations (specifying the method to execute) and arguments (the parameter list for each operation).
The custom key-value store must support three primary operations:
put(key, value): Inserts or updates the givenkeywithvalue. ReturnsNone.get(key): Retrieves the value associated withkey. If the key is not found, returnsNone.remove(key): Deletes the key-value pair associated withkeyand returns the removed value. If the key is not present, returnsNone.
Given a sequence of operations and their corresponding arguments, simulate the behavior of the hash map and return a list containing the output of each operation in order.
Constraints
- $1 \le \text{len(operations)} \le 10^4$
len(operations) == len(arguments)operations[i]is one of"put","get", or"remove".arguments[i]contains the appropriate arguments for the corresponding operation:- For
"put":[key, value] - For
"get":[key] - For
"remove":[key]
- For
- Keys can be integers, strings, or any hashable type.
- Values can be of any data type.
- Do not use built-in
dictorsettypes in your custom data structure implementation.
Output Format
Return a list of results corresponding to each operation in operations. For operations that return None (such as put or failing lookups/removals), include None in the output list.
Examples
Example 1
Input: key_value_store(['put', 'get', 'put', 'get', 'remove', 'get'], [['apple', 3], ['apple'], ['apple', 8], ['apple'], ['apple'], ['apple']])
Output: [None, 3, None, 8, 8, None]
Example 2
Input: key_value_store(['put', 'put', 'get', 'remove'], [[1, 'one'], [2, 'two'], [2], [1]])
Output: [None, None, 'two', 'one']
Example 3
Input: key_value_store(['put', 'put', 'get', 'get'], [['a', None], ['b', 0], ['a'], ['b']])
Output: [None, None, None, 0]
Hints
Hint 1
Collision handling can be implemented using separate chaining with raw lists inside fixed-capacity buckets.
Hint 2
Track the number of unique elements inserted and trigger a resize (e.g., doubling bucket count) when the load factor threshold is reached.
Hint 3
For string or integer keys, use Python's built-in `hash()` modulo the bucket count to compute bucket indices.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
To implement a custom key-value map without utilizing higher-level map structures:
- Bucketing & Chaining: Create an internal array of buckets (lists). Compute the slot index for a key using
hash(key) % capacity. Multiple keys mapping to the same slot are stored as(key, value)pairs in that bucket list (separate chaining). - Operations:
put(key, value): Check ifkeyalready exists within the target bucket. If found, overwrite its value. Otherwise, append(key, value)to the bucket and increment the item countsize. If the load factor ($\frac{\text{size}}{\text{capacity}}$) exceeds $0.75$, double the number of buckets and rehash all entries.get(key): Locate the key in its corresponding bucket and return its value. ReturnNoneif absent.remove(key): Search for the key in its bucket. If found, pop the pair, decrementsize, and return the removed value. ReturnNoneif absent.
Complexity Analysis
- Time Complexity:
put,get,remove: $O(1)$ amortized expected time, assuming uniform hash distribution. In the worst case (all keys collision into one bucket), operations degrade to $O(N)$. Dynamic resizing costs $O(N)$ amortized across operations.
- Space Complexity: $O(N)$ where $N$ is the number of active key-value pairs stored, proportional to the capacity of the array.
Python Reference Solution
from typing import List, Any
class CustomHashTable:
def __init__(self, initial_capacity: int = 8):
self.buckets = [[] for _ in range(initial_capacity)]
self.size = 0
def _index(self, key: Any) -> int:
return hash(key) % len(self.buckets)
def _find_entry_index(self, bucket: List, key: Any) -> int:
for idx, (k, _) in enumerate(bucket):
if k == key:
return idx
return -1
def _resize(self) -> None:
old_buckets = self.buckets
self.buckets = [[] for _ in range(len(old_buckets) * 2)]
for bucket in old_buckets:
for k, v in bucket:
target_bucket = self.buckets[self._index(k)]
target_bucket.append((k, v))
def put(self, key: Any, value: Any) -> None:
bucket = self.buckets[self._index(key)]
idx = self._find_entry_index(bucket, key)
if idx >= 0:
bucket[idx] = (key, value)
return
bucket.append((key, value))
self.size += 1
# Load factor threshold: 0.75
if self.size * 4 > len(self.buckets) * 3:
self._resize()
def get(self, key: Any) -> Any:
bucket = self.buckets[self._index(key)]
idx = self._find_entry_index(bucket, key)
return bucket[idx][1] if idx >= 0 else None
def remove(self, key: Any) -> Any:
bucket = self.buckets[self._index(key)]
idx = self._find_entry_index(bucket, key)
if idx < 0:
return None
_, value = bucket.pop(idx)
self.size -= 1
return value
def key_value_store(operations: List[str], arguments: List[List]) -> List[Any]:
store = CustomHashTable()
results = []
for op, args in zip(operations, arguments):
if op == "put":
store.put(args[0], args[1])
results.append(None)
elif op == "get":
results.append(store.get(args[0]))
elif op == "remove":
results.append(store.remove(args[0]))
else:
raise ValueError(f"Unsupported operation: {op}")
return results