Implement a Key-Value Store Without Built-In Maps

Hard · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Implement an in-memory key-value map class from scratch without using Python's built-in dict, set, frozenset, or any standard-library mapping or set container built on top of them. Raw fixed-size Python list arrays, equality comparisons (==), and Python's hash() function are permitted.

Your store class must handle hash collisions internally (never raising collision errors to callers), grow dynamically as entries accumulate, and support three operations in O(1) expected / amortized time:

  • put(key, value) -> None — associates value with key, overwriting the previous value if an equal key is already stored.
  • get(key) -> Any — returns the value currently stored for key, or None if key is absent.
  • remove(key) -> Any — deletes key from the map and returns its previously stored value, or returns None if key was absent.

Note that None is both a valid key and a valid stored value, so internal empty/deleted slot bookkeeping must not collide with caller data.

For automated testing, implement key_value_store(operations, arguments), which creates one empty store, executes each operation with its corresponding argument list, and returns a list of outputs (None for "put", and the method return value for "get" and "remove").

Examples

Example 1

Input:
  operations = ["put", "get", "put", "get", "remove", "get", "remove"]
  arguments  = [["theme", "light"], ["theme"], ["theme", "dark"], ["theme"], ["theme"], ["theme"], ["theme"]]
Output:
  [None, "light", None, "dark", "dark", None, None]

Explanation: "theme" is first stored with "light", then overwritten in place with "dark". The first remove("theme") deletes the entry and returns "dark"; subsequent get and remove calls see that "theme" is gone and return None.

Example 2

Input:
  operations = ["put", "put", "get", "get", "remove"]
  arguments  = [[3, "bronze"], [5, "silver"], [5], [9], [3]]
Output:
  [None, None, "silver", None, "bronze"]

Explanation: Keys 3 and 5 are stored under separate entries. get(5) retrieves "silver", get(9) returns None for an unstored key, and remove(3) deletes key 3 and returns "bronze".

Example 3

Input:
  operations = ["put", "put", "get", "get", "remove", "get"]
  arguments  = [[None, 42], ["zero", None], [None], ["zero"], [None], [None]]
Output:
  [None, None, 42, None, 42, None]

Explanation: None can be stored as a key (None -> 42) and also as a value ("zero" -> None) without interfering with internal empty-slot or tombstone markers. Removing None returns 42 and leaves later lookups for None returning None.

Constraints

  • 0 <= len(operations) == len(arguments) <= 10^5
  • Every entry in operations is "put", "get", or "remove"
  • Keys are hashable Python objects compared via ==; values can be arbitrary Python objects (including None)
  • Built-in dict, set, frozenset, and library map/set classes are forbidden

Step-by-step walkthrough

  1. Understand the problem and return contract

    We need to build a key-value store class from scratch—supporting put(key, value), get(key), and remove(key)—without using Python's built-in dict, set, or any library mapping built on top of them. Our only raw storage is fixed-length Python list arrays.

    Checking the sample tests pins down the exact return values expected by key_value_store(operations, arguments):

    • put(key, value) stores value under key (overwriting any previous value for key) and returns None.
    • get(key) returns the value currently stored under key, or None if key is missing. Notice in Example 3 that None itself can be used as both a key and a valid stored value!
    • remove(key) deletes key and returns the value that was removed, or None if key was not present.

    Keys are compared by equality (==), and we may call Python's built-in hash(key) to convert any hashable key into an integer.

  2. Turn a key into an array index

    A naive store keeps a single list of [key, value] pairs and scans it from start to finish on every call. That handles any key type with zero collisions, and we use it as a brute-force cross-check in our tests—but scanning n keys makes every operation O(n).

    To reach O(1) expected time, we allocate two parallel fixed-length lists self.keys and self.values of size capacity (a power of two, starting at 8) and compute a key's home slot directly from its hash:

    1. Call hash(key) to get a signed integer (equal keys such as 1 and 1.0 are guaranteed by Python to produce equal hashes).
    2. Scramble the hash with multiplicative Fibonacci hashing: multiply by an odd 64-bit constant near 2^64 / golden_ratio, mask to 64 unsigned bits with _MASK_64, and right-shift to keep the top log2(capacity) bits.

    Why scramble instead of taking hash(key) % capacity? In Python, hash(k) == k for small non-negative integers (0, 1, 2, ...). Without scrambling, consecutive integer keys land in one long contiguous block of slots, causing probes that hit the start of the block to walk across all of them. Taking the top bits of the 64-bit product mixes every low input bit upward via multiplication carries.

    # Odd 64-bit constant near 2^64 / golden_ratio for multiplicative Fibonacci hashing
    _GOLDEN_RATIO_64 = 0x9E3779B97F4A7C15
    _MASK_64 = (1 << 64) - 1
    
        def _allocate(self, capacity: int) -> None:
            # keys[i] holds a live key, _EMPTY, or _DELETED; values[i] holds keys[i]'s value
            self.keys = [_EMPTY] * capacity
            self.values = [None] * capacity
            # Right-shift amount to extract the top log2(capacity) bits of a 64-bit mixed hash
            index_bits = capacity.bit_length() - 1
            self.shift = 64 - index_bits
    
        def _home_slot(self, key: Any) -> int:
            """Compute the initial slot for `key` by scrambling hash(key) and taking top bits."""
            # Masking with _MASK_64 converts negative hashes into unsigned 64-bit integers.
            # Keeping the top bits (>> self.shift) mixes all lower bits upward via carries,
            # preventing consecutive integers from forming one long contiguous cluster.
            mixed_hash = (hash(key) * _GOLDEN_RATIO_64) & _MASK_64
            return mixed_hash >> self.shift
    
  3. Handle collisions with linear probing

    Even with a great hash mixer, two distinct keys will eventually map to the same home slot—a collision. Raising an exception on a collision breaks the abstraction for callers; the store must resolve collisions internally.

    We use open addressing (storing at most one entry directly inside each array slot, with no nested sub-lists) combined with linear probing: if slot is already occupied by a different key, step forward to (slot + 1) % capacity, (slot + 2) % capacity, and so on, wrapping around the end of the array until we find either our key or a slot that has never been used (_EMPTY):

    Suppose capacity = 8, and keys A, B, C all have _home_slot == 6:
      put(A, 10) -> lands at slot 6
      put(B, 20) -> slot 6 busy -> lands at slot 7
      put(C, 30) -> slot 6 busy -> slot 7 busy -> wraps to slot 0!
    
    Slots: [  C  |  _  |  _  |  _  |  _  |  _  |  A  |  B  ]
    Index:    0     1     2     3     4     5     6     7
    

    When get(C) runs later, it starts at home slot 6, sees A != C, steps to 7 (B != C), wraps to 0 (C == C), and returns 30! If we searched for a missing key D with home slot 6, we would walk 6 -> 7 -> 0 -> 1, see _EMPTY at slot 1, and know for certain D was never inserted.

  4. Why removals need tombstones

    What happens if we now call remove(B) at slot 7 in the diagram above? Look at what goes wrong if we naively reset slot 7 back to _EMPTY:

    BAD (reset slot 7 to _EMPTY):
      Slots: [  C  |  _  |  _  |  _  |  _  |  _  |  A  | _EMPTY ]
      get(C) starts at 6 (A), steps to 7 (_EMPTY) -> STOPS EARLY and claims C is missing!
    
    GOOD (mark slot 7 with a _DELETED tombstone):
      Slots: [  C  |  _  |  _  |  _  |  _  |  _  |  A  | _DELETED ]
      get(C) starts at 6 (A), walks past 7 (_DELETED), wraps to 0 (C) -> finds C!
    

    So we need two distinct private sentinel objects, _EMPTY and _DELETED (a tombstone), compared with is so that no caller key—not even None—can ever be confused with a sentinel.

    Watch out for one subtle trap when inserting after removals: if slot 7 is _DELETED and the caller calls put(C, 99) to update C, we must not stop at slot 7 and write a second copy of C there! Instead, _probe(key) records the first _DELETED slot it sees in first_available, keeps walking all the way until it either finds C at slot 0 (so put updates slot 0 in place) or hits _EMPTY at slot 1 (confirming key is genuinely new, so put can safely reuse first_available).

    class _Marker:
        """Private sentinel object so no caller's key (even None) can match a marker."""
    
        def __init__(self, name: str):
            self.name = name
    
        def __repr__(self) -> str:
            return self.name
    
    
    _EMPTY = _Marker("EMPTY")      # slot has never held a key: probes can safely stop here
    _DELETED = _Marker("DELETED")  # tombstone left by remove(): probes must keep walking past it
    
        def _probe(self, key: Any) -> Tuple[int, int]:
            """Walk `key`'s linear-probing path until finding `key` or reaching `_EMPTY`.
    
            Returns `(found_index, insert_index)`:
            - `found_index`: slot holding an equal key, or -1 if `key` is absent.
            - `insert_index`: first `_DELETED` tombstone on the path, or the stopping `_EMPTY` slot.
            """
            capacity = len(self.keys)
            slot = self._home_slot(key)
            first_available = -1
    
            # Guaranteed to terminate because rebuilds keep at least 1/3 of slots _EMPTY.
            while self.keys[slot] is not _EMPTY:
                current_key = self.keys[slot]
                if current_key is _DELETED:
                    # Remember the first reusable tombstone, but DO NOT stop yet:
                    # `key` may still sit further down the cluster!
                    if first_available == -1:
                        first_available = slot
                elif current_key == key:
                    return slot, first_available
                slot = (slot + 1) % capacity
    
            if first_available == -1:
                first_available = slot
            return -1, first_available
    
  5. Implement put, get, and remove

    With _probe handling all slot navigation, put, get, and remove become short and clear. We track two counters:

    • self.size: how many live keys are currently in the store.
    • self.filled: how many slots are not _EMPTY (live keys plus _DELETED tombstones).

    Why track self.filled separately from self.size? Because probes have to step over tombstones just like live keys! If a caller repeatedly inserts and deletes fresh keys (put(0), remove(0), put(1), remove(1), ...), self.size stays at 0 while tombstones fill every slot; if we only checked self.size, zero _EMPTY slots would remain and _probe would loop forever. Rebuilding whenever self.filled / capacity >= 2/3 (written self.filled * 3 >= len(self.keys) * 2 in exact integer math) guarantees at least 1/3 of slots are always _EMPTY.

        def put(self, key: Any, value: Any) -> None:
            """Insert or overwrite `key` with `value`."""
            found_slot, insert_slot = self._probe(key)
            if found_slot != -1:
                self.values[found_slot] = value
                return
    
            # Reusing a _DELETED tombstone keeps `self.filled` unchanged; claiming a fresh
            # _EMPTY slot increases the number of non-empty slots that probes must walk past.
            if self.keys[insert_slot] is _EMPTY:
                self.filled += 1
            self.keys[insert_slot] = key
            self.values[insert_slot] = value
            self.size += 1
    
            # Rebuild as soon as non-empty slots (live + tombstones) reach 2/3 of capacity
            # (written with integer multiplication to avoid float rounding).
            if self.filled * 3 >= len(self.keys) * 2:
                self._rebuild()
    
        def get(self, key: Any) -> Any:
            """Return the value stored for `key`, or None if `key` is not present."""
            found_slot, _ = self._probe(key)
            if found_slot == -1:
                return None
            return self.values[found_slot]
    
        def remove(self, key: Any) -> Any:
            """Delete `key` and return its old value, or None if `key` is not present."""
            found_slot, _ = self._probe(key)
            if found_slot == -1:
                return None
    
            removed_value = self.values[found_slot]
            # Leave a tombstone instead of _EMPTY so later keys in the same probe chain stay reachable.
            self.keys[found_slot] = _DELETED
            self.values[found_slot] = None
            self.size -= 1
            return removed_value
    
  6. Rebuild to grow and sweep away tombstones

    When self.filled hits 2/3 of capacity, _rebuild() allocates clean arrays whose new_capacity is the smallest power of two >= 8 and >= 4 * self.size, then re-inserts only the live keys (discarding all tombstones).

    Why >= 4 * self.size? Right after a rebuild, the table is at most 1/4 full (filled <= 1/4 * new_capacity) with zero tombstones. Before the next rebuild can trigger at 2/3 * new_capacity, callers must fill at least (2/3 - 1/4) * new_capacity = (5/12) * new_capacity fresh _EMPTY slots. Charging the O(new_capacity) rebuild work across those >= (5/12) * new_capacity operations adds only O(1) extra work per operation—amortized O(1) time—whether the rebuild grew the table for more keys or cleaned up a table clogged with tombstones!

        def _rebuild(self) -> None:
            """Rehash live entries into a clean power-of-two table at most 1/4 full."""
            old_keys = self.keys
            old_values = self.values
    
            # Choose the smallest power-of-two capacity >= MIN_CAPACITY and >= 4 * live size.
            # Starting <= 1/4 full and rebuilding at 2/3 full guarantees >= 5/12 * capacity
            # new slot fills before the next rebuild, giving amortized O(1) per operation.
            new_capacity = self.MIN_CAPACITY
            while new_capacity < 4 * self.size:
                new_capacity *= 2
    
            self._allocate(new_capacity)
            self.filled = self.size  # all tombstones are discarded during the copy
    
            for old_slot in range(len(old_keys)):
                key = old_keys[old_slot]
                if key is _EMPTY or key is _DELETED:
                    continue
                slot = self._home_slot(key)
                while self.keys[slot] is not _EMPTY:
                    slot = (slot + 1) % new_capacity
                self.keys[slot] = key
                self.values[slot] = old_values[old_slot]
    
  7. Connect the driver and trace Example 2

    Finally, key_value_store instantiates one HashMap, executes each (op, args) pair in order, and collects the return values.

    def key_value_store(operations: List[str], arguments: List[List]) -> List:
        store = HashMap()
        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"Unknown operation: {op}")
        return results
    

    Let us trace Example 2: put(3, "bronze"), put(5, "silver"), get(5), get(9), remove(3) with initial capacity = 8 (shift = 61):

    Start: keys = [_EMPTY] * 8, size = 0, filled = 0
    1. put(3, 'bronze'): _home_slot(3) == 6 -> slot 6 is _EMPTY
       keys[6] = 3, values[6] = 'bronze', size = 1, filled = 1 (1*3 < 8*2) -> appends None
    2. put(5, 'silver'): _home_slot(5) == 0 -> slot 0 is _EMPTY
       keys[0] = 5, values[0] = 'silver', size = 2, filled = 2 (2*3 < 8*2) -> appends None
    3. get(5):           _probe(5) checks slot 0, sees key 5 == 5 -> appends 'silver'
    4. get(9):           _probe(9) checks _home_slot(9) == 4, sees _EMPTY -> appends None
    5. remove(3):        _probe(3) checks slot 6, sees key 3 == 3
       keys[6] = _DELETED, values[6] = None, size = 1, filled = 2 -> appends 'bronze'
    Output: [None, None, 'silver', None, 'bronze']
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class _Marker:
        """Private sentinel object so no caller's key (even None) can match a marker."""
    
        def __init__(self, name: str):
            self.name = name
    
        def __repr__(self) -> str:
            return self.name
    
    
    _EMPTY = _Marker("EMPTY")      # slot has never held a key: probes can safely stop here
    _DELETED = _Marker("DELETED")  # tombstone left by remove(): probes must keep walking past it
    
    # Odd 64-bit constant near 2^64 / golden_ratio for multiplicative Fibonacci hashing
    _GOLDEN_RATIO_64 = 0x9E3779B97F4A7C15
    _MASK_64 = (1 << 64) - 1
    
    
    class HashMap:
        """Hash table using open addressing, linear probing, and tombstones over plain lists."""
    
        MIN_CAPACITY = 8  # capacity is always a power of two >= 8
    
        def __init__(self):
            # size: count of currently live key-value pairs
            # filled: live keys + _DELETED tombstones (all slots that are not _EMPTY)
            self.size = 0
            self.filled = 0
            self._allocate(self.MIN_CAPACITY)
    
        def _allocate(self, capacity: int) -> None:
            # keys[i] holds a live key, _EMPTY, or _DELETED; values[i] holds keys[i]'s value
            self.keys = [_EMPTY] * capacity
            self.values = [None] * capacity
            # Right-shift amount to extract the top log2(capacity) bits of a 64-bit mixed hash
            index_bits = capacity.bit_length() - 1
            self.shift = 64 - index_bits
    
        def _home_slot(self, key: Any) -> int:
            """Compute the initial slot for `key` by scrambling hash(key) and taking top bits."""
            # Masking with _MASK_64 converts negative hashes into unsigned 64-bit integers.
            # Keeping the top bits (>> self.shift) mixes all lower bits upward via carries,
            # preventing consecutive integers from forming one long contiguous cluster.
            mixed_hash = (hash(key) * _GOLDEN_RATIO_64) & _MASK_64
            return mixed_hash >> self.shift
    
        def _probe(self, key: Any) -> Tuple[int, int]:
            """Walk `key`'s linear-probing path until finding `key` or reaching `_EMPTY`.
    
            Returns `(found_index, insert_index)`:
            - `found_index`: slot holding an equal key, or -1 if `key` is absent.
            - `insert_index`: first `_DELETED` tombstone on the path, or the stopping `_EMPTY` slot.
            """
            capacity = len(self.keys)
            slot = self._home_slot(key)
            first_available = -1
    
            # Guaranteed to terminate because rebuilds keep at least 1/3 of slots _EMPTY.
            while self.keys[slot] is not _EMPTY:
                current_key = self.keys[slot]
                if current_key is _DELETED:
                    # Remember the first reusable tombstone, but DO NOT stop yet:
                    # `key` may still sit further down the cluster!
                    if first_available == -1:
                        first_available = slot
                elif current_key == key:
                    return slot, first_available
                slot = (slot + 1) % capacity
    
            if first_available == -1:
                first_available = slot
            return -1, first_available
    
        def put(self, key: Any, value: Any) -> None:
            """Insert or overwrite `key` with `value`."""
            found_slot, insert_slot = self._probe(key)
            if found_slot != -1:
                self.values[found_slot] = value
                return
    
            # Reusing a _DELETED tombstone keeps `self.filled` unchanged; claiming a fresh
            # _EMPTY slot increases the number of non-empty slots that probes must walk past.
            if self.keys[insert_slot] is _EMPTY:
                self.filled += 1
            self.keys[insert_slot] = key
            self.values[insert_slot] = value
            self.size += 1
    
            # Rebuild as soon as non-empty slots (live + tombstones) reach 2/3 of capacity
            # (written with integer multiplication to avoid float rounding).
            if self.filled * 3 >= len(self.keys) * 2:
                self._rebuild()
    
        def get(self, key: Any) -> Any:
            """Return the value stored for `key`, or None if `key` is not present."""
            found_slot, _ = self._probe(key)
            if found_slot == -1:
                return None
            return self.values[found_slot]
    
        def remove(self, key: Any) -> Any:
            """Delete `key` and return its old value, or None if `key` is not present."""
            found_slot, _ = self._probe(key)
            if found_slot == -1:
                return None
    
            removed_value = self.values[found_slot]
            # Leave a tombstone instead of _EMPTY so later keys in the same probe chain stay reachable.
            self.keys[found_slot] = _DELETED
            self.values[found_slot] = None
            self.size -= 1
            return removed_value
    
        def _rebuild(self) -> None:
            """Rehash live entries into a clean power-of-two table at most 1/4 full."""
            old_keys = self.keys
            old_values = self.values
    
            # Choose the smallest power-of-two capacity >= MIN_CAPACITY and >= 4 * live size.
            # Starting <= 1/4 full and rebuilding at 2/3 full guarantees >= 5/12 * capacity
            # new slot fills before the next rebuild, giving amortized O(1) per operation.
            new_capacity = self.MIN_CAPACITY
            while new_capacity < 4 * self.size:
                new_capacity *= 2
    
            self._allocate(new_capacity)
            self.filled = self.size  # all tombstones are discarded during the copy
    
            for old_slot in range(len(old_keys)):
                key = old_keys[old_slot]
                if key is _EMPTY or key is _DELETED:
                    continue
                slot = self._home_slot(key)
                while self.keys[slot] is not _EMPTY:
                    slot = (slot + 1) % new_capacity
                self.keys[slot] = key
                self.values[slot] = old_values[old_slot]
    
    
    def key_value_store(operations: List[str], arguments: List[List]) -> List:
        store = HashMap()
        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"Unknown operation: {op}")
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of a row of numbered gym lockers (0 through capacity - 1). Instead of writing everyone's name on a clipboard and reading the entire list every time someone asks for their bag, a hash function turns a person's name into a preferred locker number so you can walk straight there. If that locker is already taken by someone else—a collision—you follow a simple rule called linear probing (a form of open addressing, where every item lives directly inside a single array slot rather than a nested sub-list): step one locker to the right, wrapping around from the end back to locker 0, until you find an unused locker. And when someone checks out permanently, you do not make the locker look brand-new; instead you tape a "vacated — keep walking" note called a tombstone (_DELETED) on the door so anyone whose bag was placed further down the row can still walk past it and find their locker.

Why do simpler approaches fall short? Keeping an unsorted list of [key, value] pairs requires scanning up to all n stored items on every put, get, and remove, turning n operations into O(n^2) time. On the other hand, using a fixed array without collision handling fails the moment two keys map to the same index, and deleting an item by resetting its slot to _EMPTY silently severs the search path for colliding keys placed after it.

Walk through a tiny 4-locker example where keys "cat" and "dog" both hash to locker 1:

  1. put("cat", 10) checks locker 1, sees _EMPTY, and stores "cat": 10 at slot 1.
  2. put("dog", 20) checks locker 1 (occupied by "cat"), steps right to locker 2 (_EMPTY), and stores "dog": 20 at slot 2.
  3. remove("cat") finds "cat" at slot 1, replaces it with _DELETED (leaving slot 2 untouched), and returns 10.
  4. get("dog") starts at home slot 1, sees _DELETED ("keep walking!"), steps to slot 2, matches "dog", and returns 20.

Complexity

Let n be the number of live keys currently in the store, capacity be the current array length, and alpha = filled / capacity be the load factor—the fraction of array slots that are occupied by either live keys or tombstones. Our store enforces alpha < 2/3.

  • Expected time per operation: O(1). Assuming simple uniform hashing—the idealized model where each distinct key's home slot behaves like an independent uniform random draw—keeping alpha < 2/3 keeps contiguous clusters short: classical linear-probing analysis shows an average of roughly (1 + 1 / (1 - alpha)) / 2 slot checks (~2 at alpha = 2/3) for a hit and (1 + 1 / (1 - alpha)^2) / 2 (~5 at alpha = 2/3) for a miss.
  • Amortized time per put: O(1). Amortized time means the average cost per operation over any worst-case sequence of operations, spreading occasional expensive resizes across the cheap operations that paid for them. Rebuilding copies capacity slots in O(capacity) time and leaves the fresh table at most 1/4 full (new_capacity >= 4 * size) with zero tombstones; the next rebuild cannot happen until filled climbs from <= 1/4 up to 2/3 of new_capacity, which requires at least (5/12) * new_capacity new slot fills, so the rebuild work averages out to a constant number of steps per put.
  • Worst-case time per operation: O(n). Two bad things can happen on a single call: put can trigger a full O(n) table rebuild, or all n keys can hash into one contiguous cluster so _probe must inspect all n keys.
  • Space: O(M), where M is the peak number of live keys since the last rebuild. Because remove only writes tombstones without shrinking self.keys, inserting 10,000 keys allocates 32,768 slots, and even after removing all 10,000 keys those arrays remain at 32,768 slots until enough future put calls push filled to 2/3 and trigger a shrinking rebuild back down to 8.

Edge cases

  • Missing keys on get and remove: _probe hits an _EMPTY slot and returns -1, so both methods cleanly return None.
  • None or 0 stored as a key or value: Because sentinels _EMPTY and _DELETED are private _Marker instances tested with is (object identity), storing None as a key or value never collides with our internal markers.
  • Overwriting an existing key: put checks found_slot != -1 after scanning past any tombstones, updating self.values[found_slot] in place without incrementing self.size or creating duplicate keys.
  • Equal keys across numeric types (1, 1.0, True): Python guarantees 1 == 1.0 == True and hash(1) == hash(1.0) == hash(True), so our store treats them as the same key just like dict.
  • Real CPython hash collisions (hash(-1) == hash(-2)): In CPython -1 is reserved internally as an error code at the C level, so hash(-1) returns -2, colliding with hash(-2) == -2; linear probing separates them cleanly using ==.
  • Heavy insert/delete churn: Counting tombstones in self.filled forces a rebuild that sweeps away tombstones whenever filled reaches 2/3 * capacity, keeping at least 1/3 of slots _EMPTY so _probe can never enter an infinite loop.
  • float('nan') keys: Because the specification compares keys strictly with == and nan == nan is False under IEEE-754 floating-point rules, a nan key will not match itself on a later get (Python's built-in dict checks a is b or a == b first).

Common mistakes

  • Setting a deleted slot back to _EMPTY: Breaks the probe chain for any colliding key placed past that slot, causing get to falsely return None and put to insert duplicate copies.
  • Inserting into the first _DELETED tombstone immediately: If you stop probing as soon as you see a tombstone during put(key, val), you miss an existing copy of key sitting further down the cluster and corrupt the table with two entries for the same key.
  • Checking load factor with self.size instead of self.filled: Repeated put + remove pairs leave self.size small while filling 100% of slots with _DELETED, turning while self.keys[slot] is not _EMPTY: into an infinite loop.
  • Using raw hash(key) % capacity with integer keys: Small integers hash to themselves in Python, creating a giant contiguous cluster (primary clustering) where misses near the front must scan the whole run.
  • Claiming unqualified worst-case O(1) in the interview: Both open addressing and separate chaining are O(1) expected (and amortized across resizes), while their worst-case single-operation cost is O(n).

Alternative approaches

  • Separate chaining: Store a small list (bucket) at each of the capacity array indices and append colliding [key, value] pairs to buckets[home_slot]. Deletion simply removes the pair from its bucket list—no tombstones needed—at the cost of extra per-bucket list allocations and pointer chasing.
  • Open addressing with backward-shift deletion: Instead of leaving _DELETED tombstones on remove, walk forward through the contiguous cluster and shift back any entry whose _home_slot lies cyclically at or before the vacated gap. Lookups stay fast without tombstones, though remove logic is trickier to get bug-free under wraparound.
  • Balanced binary search tree (e.g., Red-Black or AVL tree): Guarantees strict worst-case O(log n) time per put, get, and remove with zero hash functions or collisions, but requires keys to support < ordering rather than equality alone.

Follow-up questions

  • Suppose an interviewer argues that bucket chaining fails the O(1) requirement; how do you clarify the complexity guarantees and compare them with open addressing? Acknowledge immediately that in the worst case, if all n keys hash to the same bucket, separate chaining degrades to scanning an n-element list in O(n) time—and clarify that when engineers say a hash table is O(1), they mean expected O(1) under uniform hashing and amortized O(1) across table resizes when n / capacity is kept bounded. Then be completely transparent that our open-addressing linear-probing store has the exact same asymptotic guarantees: expected O(1), amortized O(1) across _rebuild() calls, and worst-case O(n) when all keys collide into one cluster (plus O(n) on the single put that triggers a rebuild). Open addressing improves cache locality and avoids per-slot list objects, not worst-case Big-O.
  • What happens to throughput if an adversary crafts inputs that all map to the same home index, and how can a hash table mitigate that attack? Every put and get walks the entire n-element cluster, degrading n requests from O(n) total time to O(n^2) CPU time—a denial-of-service attack known as hash flooding. The standard defense is keyed cryptographic hashing such as SipHash (a fast hash function parameterized by a secret per-process random 128-bit key, which CPython uses for str and bytes since Python 3.4 so attackers cannot predict collisions offline). Note that multiplying hash(key) by a secret seed is not enough if the attacker sends integers whose hash(key) values already collide before our mixer runs (for instance, multiples of CPython's Mersenne prime 2^61 - 1), so untrusted inputs should be hashed directly from their raw bytes with a secret key—or else switch Separate Chaining buckets that exceed a small threshold (say 8 entries) into balanced search trees (O(log n) worst case for comparable keys, as Java's HashMap does).
  • Which hashing schemes guarantee inspecting only O(1) array positions during lookups even in the strict worst case? Use cuckoo hashing—a scheme with two arrays T1, T2 and two independent hash functions h1, h2 that maintains the invariant that every stored key k lives at either T1[h1(k)] or T2[h2(k)] and nowhere else, so get(k) inspects at most 2 slots in the strict worst case (O(1) worst-case lookup!). When put(k, v) finds both candidate slots occupied, it places k in T1[h1(k)] and kicks the previous occupant out to its alternate slot in T2, repeating along a chain of displacements; if a cycle occurs (exceeding O(log n) kicks), the table picks fresh random hash seeds and rebuilds (O(1) expected amortized put when total load stays below 50%). If the key set is static and known upfront, two-level perfect hashing (Fredman-Komlos-Szemeredi) sizes each bucket's secondary table quadratically (b_i^2) with a collision-free secondary hash, giving worst-case O(1) get in O(n) total memory.
  • How would you adapt this data structure so multiple threads can safely read and mutate entries concurrently? Concurrent calls to put, remove, or _rebuild race on shared array slots, counters, and array references (even in CPython, where the Global Interpreter Lock (GIL)—an interpreter mutex allowing only one thread to execute Python bytecodes at a time—can switch threads mid-method between _probe and slot assignment, and is optional in free-threaded Python 3.13+). The simplest fix wraps put, get, and remove in a single threading.Lock, serializing all callers. To scale read-heavy workloads, a readers-writer lock allows many concurrent get calls whenever no put/remove is mutating the store. To scale concurrent writers as well, use lock striping—partitioning the store into S independent sub-tables (for example S = 64 shards selected by the top 6 bits of the scrambled hash), each with its own lock and independent _rebuild(), so threads operating on different shards run in parallel without blocking a global resize.

Follow-up questions

Similar questions

More Ease interview questions

All 1 Ease questions →