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 with numBuckets buckets.
  • put(key, value) — Associates value with key. When key is already stored in the table, its previous value is overwritten in place.
  • get(key) — Returns the value currently associated with key, or -1 when key is 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^4
  • operations[0] == "HashTable", and for i >= 1, operations[i] is either "put" or "get".
  • numBuckets >= 1
  • Every key is a non-null hashable object (such as an int or str).
  • Stored value items may include falsy Python values (0, "", False, None), which must be returned intact on get rather than turned into -1.
  • Built-in hash table or set containers may not be used.

Step-by-step walkthrough

  1. Understand the API and judge format

    Our task is to build an in-memory key-value map from scratch without Python's built-in dict or set types:

    • HashTable(numBuckets) allocates an internal bucket array of size numBuckets.
    • put(key, value) stores (key, value), updating the existing entry in place when key is already present.
    • get(key) looks up key and returns its stored value, or -1 when key is absent.

    Keys are non-null hashable values (such as integers and strings), distinct keys may land on the same bucket, and both put and get should run in O(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 collecting None for "HashTable" / "put" calls alongside the returned value (or -1) for "get" calls.

  2. 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 every put and get. That works great as a brute-force reference in unit tests, yet with n stored keys each lookup or update inspects up to n pairs — O(n) per operation and O(n^2) over n operations.

    Achieving O(1) average time requires jumping directly to a tiny shortlist of candidates instead of scanning all n keys.

  3. Key idea: map keys to buckets with modulo and chain collisions

    Instead of one big list, we allocate an array of m short lists called buckets. Given any key, 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, with 5 buckets, 2 % 5 == 2 and 7 % 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 only hash(pair[0]) == hash(key): unequal keys can share the exact same integer hash (in CPython, hash(-1) == hash(-2) == -2!). - Never compare with is: equal strings or large integers created separately at runtime are distinct objects in memory.

  4. Build the bucket array and put/get methods

    Three Python-specific details keep the code clean and bug-free:

    1. Independent bucket lists: Allocate buckets in a loop (buckets.append([])), never [[]] * count. In Python, [[]] * count aliases the exact same inner list across all count slots!
    2. Mutable [key, value] pairs: Representing each entry as a 2-element list [key, value] (instead of an immutable tuple) lets put overwrite pair[1] = value in place without changing self.size.
    3. Negative hashes: Python's % operator with a positive divisor len(self.buckets) always returns 0 <= index < len(self.buckets), even when hash(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
    
  5. Keep chains short: load factor and rehashing on resize

    If numBuckets never grew — say starting at 2 buckets while 2,000 keys are inserted — each bucket chain would average 1,000 pairs and lookups would degrade back to O(n).

    The load factor size / len(buckets) tracks the average number of keys per bucket. Whenever adding a new key pushes load_factor past 0.75, we double len(buckets) and rehash every stored pair into the fresh bucket array. Copying old bucket i straight into new bucket i would be wrong because doubling the divisor changes hash(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 later get calls 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 size pairs in O(size) time, doubling the bucket count (5 -> 10 -> 20 -> ...) means total pair moves across n insertions sum to roughly n / 2 + n / 4 + n / 8 + ... < n, keeping put O(1) amortized time.

  6. Write the judge driver

    The driver iterates over (op, args) pairs in parallel, instantiating HashTable and 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 results
    
  7. Trace Example 3 (collision in bucket 2)

    Let's trace operations = ['HashTable', 'put', 'put', 'get', 'get', 'get'] with arguments = [[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 -1
    

    Returned list: [None, None, None, 'two', 'seven', -1].

  8. 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: get runs in O(1) expected time and put runs in O(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 averages n / m <= 0.75 entries, so scanning one bucket inspects fewer than one pair on average; doubling m performs an O(n) rehash (recomputing hash(key) % new_m for every stored pair), whose cumulative cost across n insertions is 1 + 2 + 4 + ... + n < 2n, or O(1) per put. In the pathological worst case where every key hashes into one bucket, a single call takes O(n) time.
  • Space: O(n + m_0), where m_0 is the initial numBuckets given to the constructor. Each distinct key occupies one [key, value] pair (O(n)), and after any resize m <= 2 * (n / 0.75) ≈ 2.67n, which is also O(n).

Edge cases

  • Bucket index collisions (2, 7, and absent 12 with 5 buckets): Stored pairs coexist in bucket 2, while an uninserted colliding key still returns -1 (Example 3).
  • Unequal keys sharing the exact same hash() value: In CPython hash(-1) == hash(-2) == -2; testing pair[0] == key keeps -1 and -2 separate.
  • Overwriting an existing key (put(7, "draft") then put(7, "published")): Updates pair[1] in place without duplicating the key or inflating self.size (Example 2).
  • Falsy stored values (0, "", False, None): Returning pair[1] directly upon matching pair[0] == key preserves 0 or "" rather than replacing them with MISSING = -1.
  • Distinct types (1 vs "1"): Because 1 == "1" is False in Python, both keys coexist independently.
  • Non-positive numBuckets (0): Guarded via max(1, num_buckets) so modulo % never triggers ZeroDivisionError.

Common mistakes

  • Allocating buckets via [[]] * num_buckets: Aliases the exact same inner list across all num_buckets positions, turning the whole table into a single shared list of duplicate references!
  • Checking hash(pair[0]) == hash(key) instead of pair[0] == key: Corrupts entries whenever two distinct keys produce equal hash integers (such as -1 and -2 in CPython).
  • Using is instead of == to compare keys: Fails to match equal strings or large integers constructed dynamically at runtime.
  • Copying buckets during _resize without rehashing: Because hash(key) % m shifts when m doubles from 5 to 10 (for example, 7 % 5 == 2 whereas 7 % 10 == 7), skipping bucket recomputation strands stored keys in the wrong buckets.
  • Appending on put without scanning the chain first: Leaves stale earlier [key, old_value] pairs at the front of the bucket so get returns outdated values and self.size overcounts.
  • Writing return value or -1 in get: Converts valid falsy values such as 0, "", or False into -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 either key or an empty slot. This avoids per-bucket list allocations and improves CPU cache locality (Python's built-in dict uses open addressing), though it requires keeping the load factor strictly below 1.0 (typically <= 0.66).
  • Self-balancing binary search tree (AVL or Red-Black tree): Guarantees worst-case O(log n) put and get without hash functions or resize pauses and maintains keys in sorted order, at the cost of requiring < ordering on keys and slower average lookups than O(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 == b implies hash(a) == hash(b)), cheap to compute (O(1) for fixed-width ints or O(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 taking key % 100 on multiples of 20 — those few chains grow proportional to n and put/get degrade from O(1) toward O(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 / numBuckets equals the expected chain length, so each lookup examines roughly 1 + alpha entries. Choosing too few buckets (large alpha) lengthens chains and increases key comparisons, whereas choosing far too many buckets (tiny alpha) wastes memory and hurts cache locality. Resizing by doubling numBuckets whenever alpha > 0.75 keeps chain lengths below 1 on average while bounding empty overhead, and pre-sizing numBuckets near expected_keys / 0.75 avoids 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 > 1 remains 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 as alpha approaches 1.0, forcing earlier resizes around 0.5–0.7.
  • How does slot probing work under open addressing, and why do clustering and deletions require special care? When start = hash(key) % m holds a different key, open addressing checks fallback indices until finding key or a never-used empty slot: linear probing tests start + 1, start + 2, ... (great cache locality), quadratic probing tests start + 1^2, start + 2^2, ..., and double hashing steps by i * 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 to empty without cutting off lookups for keys probed past that slot; instead, deleted slots must be marked with a tombstone sentinel that get steps over and put reclaims, with periodic rehashes to purge accumulated tombstones.

Follow-up questions

Similar questions

More Paradromics interview questions

All 3 Paradromics questions →