Custom Hash Map with Put and Get
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Build an in-memory hash map class HashTable from first principles without relying on built-in map or set containers (dict, set, defaultdict, and similar types are disallowed, though Python's hash(key) function may be used to compute integer hash codes).
Your HashTable class must support three operations:
HashTable(numBuckets)— Initializes storage starting withnumBucketsbuckets.put(key, value)— Associatesvaluewithkey. Whenkeyis already stored in the table, its previous value is overwritten in place.get(key)— Returns the value currently associated withkey, or-1whenkeyis not stored in the table.
Removing keys (delete / remove) is not part of this problem. Distinct keys that map to the same bucket index must coexist without overwriting one another, and both put and get should run in O(1) expected / amortized time even when many more keys are inserted than the starting numBuckets.
The automated judge exercises your implementation through the driver function:
def hash_table_operations(operations: List[str], arguments: List[List]) -> List:
For each index i, operations[i] names "HashTable", "put", or "get", and arguments[i] supplies that call's argument list ([numBuckets], [key, value], or [key]). Return a list of equal length recording None for "HashTable" and "put" calls and the looked-up result (or -1) for "get" calls.
Examples
Example 1
Input:
operations = ["HashTable", "put", "put", "get", "get"]
arguments = [[4], ["id", 42], ["port", 8080], ["id"], ["host"]]
Output: [None, None, None, 42, -1]
Explanation: After creating a 4-bucket table and storing "id" -> 42 and "port" -> 8080, querying "id" returns 42 while querying the absent key "host" returns -1.
Example 2
Input:
operations = ["HashTable", "put", "get", "put", "get"]
arguments = [[2], [7, "draft"], [7], [7, "published"], [7]]
Output: [None, None, "draft", None, "published"]
Explanation: Calling put a second time with existing key 7 replaces "draft" with "published", so the second get(7) returns "published".
Example 3
Input:
operations = ["HashTable", "put", "put", "get", "get", "get"]
arguments = [[5], [2, "two"], [7, "seven"], [2], [7], [12]]
Output: [None, None, None, "two", "seven", -1]
Explanation: With 5 buckets, keys 2, 7, and 12 all hash to bucket index 2 (2 % 5 == 7 % 5 == 12 % 5 == 2). Collision handling keeps [2, "two"] and [7, "seven"] distinct while reporting -1 for the uninserted colliding key 12.
Constraints
1 <= len(operations) == len(arguments) <= 10^4operations[0] == "HashTable", and fori >= 1,operations[i]is either"put"or"get".numBuckets >= 1- Every
keyis a non-null hashable object (such as anintorstr). - Stored
valueitems may include falsy Python values (0,"",False,None), which must be returned intact ongetrather than turned into-1. - Built-in hash table or set containers may not be used.
Step-by-step walkthrough
Understand the API and judge format
Our task is to build an in-memory key-value map from scratch without Python's built-in
dictorsettypes:HashTable(numBuckets)allocates an internal bucket array of sizenumBuckets.put(key, value)stores(key, value), updating the existing entry in place whenkeyis already present.get(key)looks upkeyand returns its stored value, or-1whenkeyis absent.
Keys are non-null hashable values (such as integers and strings), distinct keys may land on the same bucket, and both
putandgetshould run inO(1)expected / amortized time.The judge invokes our class via
hash_table_operations(operations, arguments), stepping through"HashTable","put", and"get"calls in order and collectingNonefor"HashTable"/"put"calls alongside the returned value (or-1) for"get"calls.Why one flat list of pairs is too slow
A minimal key-value store could hold a single list of
[key, value]pairs, scanning from start to end on everyputandget. That works great as a brute-force reference in unit tests, yet withnstored keys each lookup or update inspects up tonpairs —O(n)per operation andO(n^2)overnoperations.Achieving
O(1)average time requires jumping directly to a tiny shortlist of candidates instead of scanning allnkeys.Key idea: map keys to buckets with modulo and chain collisions
Instead of one big list, we allocate an array of
mshort lists called buckets. Given anykey, we compute its bucket index deterministically from the key:bucket_index = hash(key) % len(buckets)Python's
hash(key)helper turns an integer or string into an integer hash code and guarantees that equal keys (a == b) always share the same hash code.Two unequal keys can still produce the same
bucket_index(for example, with5buckets,2 % 5 == 2and7 % 5 == 2). That event is a collision. Under separate chaining, each bucket is a short list of[key, value]pairs, so colliding keys live side by side in that bucket's list:buckets (len = 5) after put(2, "two"), put("id", 42), put(7, "seven"): index 0: [ ] index 1: [ ] index 2: [ [2, "two"], [7, "seven"] ] <- 2 and 7 collided here; chain stores both! index 3: [ ["id", 42] ] <- assuming hash("id") % 5 == 3 index 4: [ ]While scanning a bucket's chain, always compare the keys themselves with
pair[0] == key: - Never compare onlyhash(pair[0]) == hash(key): unequal keys can share the exact same integer hash (in CPython,hash(-1) == hash(-2) == -2!). - Never compare withis: equal strings or large integers created separately at runtime are distinct objects in memory.Build the bucket array and put/get methods
Three Python-specific details keep the code clean and bug-free:
- Independent bucket lists: Allocate buckets in a loop (
buckets.append([])), never[[]] * count. In Python,[[]] * countaliases the exact same inner list across allcountslots! - Mutable
[key, value]pairs: Representing each entry as a 2-element list[key, value](instead of an immutable tuple) letsputoverwritepair[1] = valuein place without changingself.size. - Negative hashes: Python's
%operator with a positive divisorlen(self.buckets)always returns0 <= index < len(self.buckets), even whenhash(key)is negative. (Languages like C++ or Java keep the dividend's negative sign and need floor-modulo or bitmasking.)
MISSING = -1 MAX_LOAD_FACTOR = 0.75 def _make_empty_buckets(count: int) -> List[List[List[Any]]]: """Allocate `count` independent empty bucket lists.""" # Build each inner list separately; `[[]] * count` would alias the exact # same list object across every slot! buckets: List[List[List[Any]]] = [] for _ in range(count): buckets.append([]) return buckets class HashTable: """Hash map using separate chaining: each bucket stores [key, value] pairs.""" def __init__(self, num_buckets: int): # Clamp to at least 1 bucket so `% len(self.buckets)` never divides by 0. initial_count = max(1, num_buckets) # buckets: array of chains, e.g. [[], [], [[2, "two"], [7, "seven"]], [], []] self.buckets: List[List[List[Any]]] = _make_empty_buckets(initial_count) # size: total number of distinct keys currently stored across all buckets self.size = 0 def _get_bucket(self, key: Any) -> List[List[Any]]: # Python's `%` with a positive divisor always yields 0 <= index < len(buckets), # even when `hash(key)` is negative. bucket_index = hash(key) % len(self.buckets) return self.buckets[bucket_index] def put(self, key: Any, value: Any) -> None: bucket = self._get_bucket(key) # Phase 1: check if `key` already exists in this bucket; compare keys # with `==` (not hashes, which can collide, and not `is` identity). for pair in bucket: if pair[0] == key: pair[1] = value return # Phase 2: `key` is new; append [key, value] and update distinct key count. bucket.append([key, value]) self.size += 1 # Phase 3: if average chain length exceeds 0.75, double buckets and rehash. load_factor = self.size / len(self.buckets) if load_factor > MAX_LOAD_FACTOR: self._resize(2 * len(self.buckets)) def get(self, key: Any) -> Any: bucket = self._get_bucket(key) for pair in bucket: if pair[0] == key: return pair[1] return MISSING- Independent bucket lists: Allocate buckets in a loop (
Keep chains short: load factor and rehashing on resize
If
numBucketsnever grew — say starting at2buckets while2,000keys are inserted — each bucket chain would average1,000pairs and lookups would degrade back toO(n).The load factor
size / len(buckets)tracks the average number of keys per bucket. Whenever adding a new key pushesload_factorpast0.75, we doublelen(buckets)and rehash every stored pair into the fresh bucket array. Copying old bucketistraight into new bucketiwould be wrong because doubling the divisor changeshash(key) % len(buckets):Before resize (5 buckets): key = 7 -> 7 % 5 = 2 (stored in bucket 2) After resize (10 buckets): key = 7 -> 7 % 10 = 7 (must move to bucket 7!)Recomputing
_get_bucket(key)for every stored pair ensures latergetcalls always look in the right place:def _resize(self, new_bucket_count: int) -> None: """Allocate a larger bucket array and rehash every existing [key, value] pair.""" old_buckets = self.buckets self.buckets = _make_empty_buckets(new_bucket_count) # Every key's `hash(key) % len(self.buckets)` may change when the divisor # doubles, so recompute the target bucket for each stored pair. for old_bucket in old_buckets: for pair in old_bucket: key = pair[0] target_bucket = self._get_bucket(key) target_bucket.append(pair)Although a single resize moves
sizepairs inO(size)time, doubling the bucket count (5 -> 10 -> 20 -> ...) means total pair moves acrossninsertions sum to roughlyn / 2 + n / 4 + n / 8 + ... < n, keepingputO(1)amortized time.Write the judge driver
The driver iterates over
(op, args)pairs in parallel, instantiatingHashTableand appending each call's output:def hash_table_operations(operations: List[str], arguments: List[List]) -> List: table: Optional[HashTable] = None results: List[Any] = [] for op, args in zip(operations, arguments): if op == "HashTable": table = HashTable(args[0]) results.append(None) elif op == "put": assert table is not None table.put(args[0], args[1]) results.append(None) elif op == "get": assert table is not None results.append(table.get(args[0])) else: raise ValueError(f"Unknown operation: {op!r}") return resultsTrace Example 3 (collision in bucket 2)
Let's trace
operations = ['HashTable', 'put', 'put', 'get', 'get', 'get']witharguments = [[5], [2, 'two'], [7, 'seven'], [2], [7], [12]](non-negative small ints hash to themselves in Python):1. HashTable(5) buckets = [[], [], [], [], []], size = 0 -> output None 2. put(2, 'two') 2 % 5 = 2 -> bucket 2 becomes [[2, 'two']] size = 1, load_factor = 1/5 = 0.20 <= 0.75 -> output None 3. put(7, 'seven') 7 % 5 = 2 -> collision in bucket 2! check [2, 'two']: 2 == 7 is False -> append bucket 2 becomes [[2, 'two'], [7, 'seven']] size = 2, load_factor = 2/5 = 0.40 <= 0.75 -> output None 4. get(2) 2 % 5 = 2 -> pair 0 matches 2 == 2 -> output 'two' 5. get(7) 7 % 5 = 2 -> skip [2, 'two'], pair 1 matches 7 -> output 'seven' 6. get(12) 12 % 5 = 2 -> scan sees 2 != 12 and 7 != 12 -> output -1Returned list:
[None, None, None, 'two', 'seven', -1].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple # Sentinel returned by get() when a key is not stored in the table. MISSING = -1 # Resize threshold: double the bucket array when size / len(buckets) > 0.75. MAX_LOAD_FACTOR = 0.75 def _make_empty_buckets(count: int) -> List[List[List[Any]]]: """Allocate `count` independent empty bucket lists.""" # Build each inner list separately; `[[]] * count` would alias the exact # same list object across every slot! buckets: List[List[List[Any]]] = [] for _ in range(count): buckets.append([]) return buckets class HashTable: """Hash map using separate chaining: each bucket stores [key, value] pairs.""" def __init__(self, num_buckets: int): # Clamp to at least 1 bucket so `% len(self.buckets)` never divides by 0. initial_count = max(1, num_buckets) # buckets: array of chains, e.g. [[], [], [[2, "two"], [7, "seven"]], [], []] self.buckets: List[List[List[Any]]] = _make_empty_buckets(initial_count) # size: total number of distinct keys currently stored across all buckets self.size = 0 def _get_bucket(self, key: Any) -> List[List[Any]]: # Python's `%` with a positive divisor always yields 0 <= index < len(buckets), # even when `hash(key)` is negative. bucket_index = hash(key) % len(self.buckets) return self.buckets[bucket_index] def put(self, key: Any, value: Any) -> None: bucket = self._get_bucket(key) # Phase 1: check if `key` already exists in this bucket; compare keys # with `==` (not hashes, which can collide, and not `is` identity). for pair in bucket: if pair[0] == key: pair[1] = value return # Phase 2: `key` is new; append [key, value] and update distinct key count. bucket.append([key, value]) self.size += 1 # Phase 3: if average chain length exceeds 0.75, double buckets and rehash. load_factor = self.size / len(self.buckets) if load_factor > MAX_LOAD_FACTOR: self._resize(2 * len(self.buckets)) def get(self, key: Any) -> Any: bucket = self._get_bucket(key) for pair in bucket: if pair[0] == key: return pair[1] return MISSING def _resize(self, new_bucket_count: int) -> None: """Allocate a larger bucket array and rehash every existing [key, value] pair.""" old_buckets = self.buckets self.buckets = _make_empty_buckets(new_bucket_count) # Every key's `hash(key) % len(self.buckets)` may change when the divisor # doubles, so recompute the target bucket for each stored pair. for old_bucket in old_buckets: for pair in old_bucket: key = pair[0] target_bucket = self._get_bucket(key) target_bucket.append(pair) def hash_table_operations(operations: List[str], arguments: List[List]) -> List: table: Optional[HashTable] = None results: List[Any] = [] for op, args in zip(operations, arguments): if op == "HashTable": table = HashTable(args[0]) results.append(None) elif op == "put": assert table is not None table.put(args[0], args[1]) results.append(None) elif op == "get": assert table is not None results.append(table.get(args[0])) else: raise ValueError(f"Unknown operation: {op!r}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine organizing a parcel room for thousands of packages. Piling every package onto one long shelf forces you to read labels one by one from end to end whenever someone arrives. Instead, suppose you set up 100 numbered bins (00 through 99) and place each package into bin tracking_id % 100. That deterministic formula mapping a key to an integer is a hash function (a calculation that converts any key into an integer and guarantees equal keys always produce the exact same integer), and each bin is a bucket (one slot of our internal list array). Whenever two unequal keys map to the same bucket index — a collision — keeping a short list of [key, value] pairs inside that bucket is separate chaining, and doubling the bucket count whenever the load factor (the ratio stored_keys / num_buckets, representing average chain length) exceeds 0.75 keeps every bucket list tiny.
Why do simpler shortcuts fail? Storing all [key, value] pairs in a single flat list forces every put and get to scan up to n entries, costing O(n) per operation and O(n^2) across n operations. Conversely, assigning buckets[hash(key) % m] = value directly without storing keys or chaining collisions silently clobbers an earlier key's value whenever another key lands on the same bucket index!
Let's trace HashTable(5) with put(2, "two"), put(7, "seven"), put(2, "TWO"), and get(7):
1. put(2, "two"): 2 % 5 = 2; bucket 2 becomes [[2, "two"]] (size = 1, load factor 1/5 = 0.20).
2. put(7, "seven"): 7 % 5 = 2 (collision in bucket 2); scan sees 2 != 7, so we append [7, "seven"], making bucket 2 [[2, "two"], [7, "seven"]] (size = 2, load factor 2/5 = 0.40, matching Example 3).
3. put(2, "TWO"): 2 % 5 = 2; scan matches pair[0] == 2 and updates in place to [[2, "TWO"], [7, "seven"]] (size stays 2).
4. get(7): 7 % 5 = 2; scan skips [2, "TWO"], matches pair[0] == 7, and returns "seven".
Complexity
Let n be the number of distinct keys currently stored and m be the current bucket count (len(self.buckets)).
- Time:
getruns inO(1)expected time andputruns inO(1)expected amortized time (average cost per call over a sequence of calls, even though occasional calls perform extra resizing work). When keys distribute uniformly, each bucket averagesn / m <= 0.75entries, so scanning one bucket inspects fewer than one pair on average; doublingmperforms anO(n)rehash (recomputinghash(key) % new_mfor every stored pair), whose cumulative cost acrossninsertions is1 + 2 + 4 + ... + n < 2n, orO(1)perput. In the pathological worst case where every key hashes into one bucket, a single call takesO(n)time. - Space:
O(n + m_0), wherem_0is the initialnumBucketsgiven to the constructor. Each distinct key occupies one[key, value]pair (O(n)), and after any resizem <= 2 * (n / 0.75) ≈ 2.67n, which is alsoO(n).
Edge cases
- Bucket index collisions (
2,7, and absent12with5buckets): Stored pairs coexist in bucket2, while an uninserted colliding key still returns-1(Example 3). - Unequal keys sharing the exact same
hash()value: In CPythonhash(-1) == hash(-2) == -2; testingpair[0] == keykeeps-1and-2separate. - Overwriting an existing key (
put(7, "draft")thenput(7, "published")): Updatespair[1]in place without duplicating the key or inflatingself.size(Example 2). - Falsy stored values (
0,"",False,None): Returningpair[1]directly upon matchingpair[0] == keypreserves0or""rather than replacing them withMISSING = -1. - Distinct types (
1vs"1"): Because1 == "1"isFalsein Python, both keys coexist independently. - Non-positive
numBuckets(0): Guarded viamax(1, num_buckets)so modulo%never triggersZeroDivisionError.
Common mistakes
- Allocating buckets via
[[]] * num_buckets: Aliases the exact same inner list across allnum_bucketspositions, turning the whole table into a single shared list of duplicate references! - Checking
hash(pair[0]) == hash(key)instead ofpair[0] == key: Corrupts entries whenever two distinct keys produce equal hash integers (such as-1and-2in CPython). - Using
isinstead of==to compare keys: Fails to match equal strings or large integers constructed dynamically at runtime. - Copying buckets during
_resizewithout rehashing: Becausehash(key) % mshifts whenmdoubles from5to10(for example,7 % 5 == 2whereas7 % 10 == 7), skipping bucket recomputation strands stored keys in the wrong buckets. - Appending on
putwithout scanning the chain first: Leaves stale earlier[key, old_value]pairs at the front of the bucket sogetreturns outdated values andself.sizeovercounts. - Writing
return value or -1inget: Converts valid falsy values such as0,"", orFalseinto-1.
Alternative approaches
- Open addressing: Rather than allocating a sub-list per bucket, open addressing stores
[key, value]entries directly inside one flat slot array and resolves collisions by stepping along a deterministic probe sequence until finding eitherkeyor an empty slot. This avoids per-bucket list allocations and improves CPU cache locality (Python's built-indictuses open addressing), though it requires keeping the load factor strictly below1.0(typically<= 0.66). - Self-balancing binary search tree (AVL or Red-Black tree): Guarantees worst-case
O(log n)putandgetwithout hash functions or resize pauses and maintains keys in sorted order, at the cost of requiring<ordering on keys and slower average lookups thanO(1)hashing.
Follow-up questions
- Which properties define a high-quality hash function, and what happens to lookup speed when keys hash unevenly? A strong hash function is deterministic, consistent with equality (
a == bimplieshash(a) == hash(b)), cheap to compute (O(1)for fixed-width ints orO(len(s))for strings), and scatters realistic inputs evenly across buckets so small input edits land in unrelated buckets. When keys clump into a handful of buckets — such as hashing strings only by their first letter or takingkey % 100on multiples of20— those few chains grow proportional tonandput/getdegrade fromO(1)towardO(n). Production runtimes like Python also seed string hashes randomly per process to thwart adversarial hash-flooding attacks. - How do the bucket count and load-factor threshold trade memory footprint against collision cost? Under uniform hashing, the load factor
alpha = n / numBucketsequals the expected chain length, so each lookup examines roughly1 + alphaentries. Choosing too few buckets (largealpha) lengthens chains and increases key comparisons, whereas choosing far too many buckets (tinyalpha) wastes memory and hurts cache locality. Resizing by doublingnumBucketswheneveralpha > 0.75keeps chain lengths below1on average while bounding empty overhead, and pre-sizingnumBucketsnearexpected_keys / 0.75avoids early rehashes when final cardinality is known. - What are the main trade-offs between separate chaining and open addressing for resolving bucket collisions? Separate chaining keeps a dynamic list per bucket: it is simple to code, tolerates high load factors gracefully (even
alpha > 1remains functional), and supports key removal by deleting one node from its bucket list, at the expense of extra object headers and pointer chasing. Open addressing packs entries directly into a single contiguous array for superior CPU cache performance and lower memory overhead, yet probe lengths spike sharply asalphaapproaches1.0, forcing earlier resizes around0.5–0.7. - How does slot probing work under open addressing, and why do clustering and deletions require special care? When
start = hash(key) % mholds a different key, open addressing checks fallback indices until findingkeyor a never-used empty slot: linear probing testsstart + 1, start + 2, ...(great cache locality), quadratic probing testsstart + 1^2, start + 2^2, ..., and double hashing steps byi * hash2(key). Linear probing suffers from primary clustering, where adjacent occupied slots coalesce into long runs that capture even more hashes, and non-coprime step sizes can cycle without visiting empty slots. Deletions also cannot simply reset a slot toemptywithout cutting off lookups for keys probed past that slot; instead, deleted slots must be marked with a tombstone sentinel thatgetsteps over andputreclaims, with periodic rehashes to purge accumulated tombstones.
Follow-up questions
- Which properties define a high-quality hash function, and what happens to lookup speed when keys hash unevenly?
- How do the bucket count and load-factor threshold trade memory footprint against collision cost?
- What are the main trade-offs between separate chaining and open addressing for resolving bucket collisions?
- How does slot probing work under open addressing, and why do clustering and deletions require special care?
Similar questions
- Count Distinct Staircase Climb Sequences
- Database Paradigms, Container Orchestration, and Python Performance
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance