Implement a string-to-integer hash table with chaining and load-factor resizing

Quick Overview

Implement a string-to-integer hash table from scratch with separate chaining, insert, lookup, delete, a sorted key listing, and automatic doubling when the load factor passes 0.75. It tests bucket indexing, rehashing on resize, amortized complexity, and edge cases such as updates and removals.

Implement a string-to-integer hash table with chaining and load-factor resizing

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design and implement a hash table from scratch that supports insertion, lookup, and deletion of key-value pairs. Keys are strings and values are integers. The hash table should use chaining (a list of entries per bucket) as the collision resolution strategy. When the load factor (number of entries divided by number of buckets) exceeds `0.75` after an insertion, the table must automatically resize by doubling its capacity and rehashing all existing entries. If a key already exists during insertion, its value should be updated. Lookups for missing keys return `-1`. Removal returns a boolean indicating whether the key was found. Implement a class `HashTable` whose constructor takes the initial number of buckets, with these methods: - `put(key: str, value: int) -> None`: insert or update a key-value pair. If the load factor exceeds 0.75 after the insertion, the table resizes by doubling its capacity and rehashing all entries. - `get(key: str) -> int`: return the value associated with the key, or -1 if the key is not found. - `remove(key: str) -> bool`: remove the key-value pair for the key. Return `True` if the key was found and removed, `False` otherwise. - `getKeys() -> List[str]`: return a sorted list of all keys currently stored in the table. - `getSize() -> int`: return the number of key-value pairs currently stored. - `getCapacity() -> int`: return the current number of buckets. Each example below is a sequence of calls on one table. The first list holds the method names, the second their arguments, and the output holds each call's return value (`null` for the constructor and for `put`). Starting from two buckets: ```text Input: ["HashTable", "put", "put", "getCapacity", "put", "getCapacity", "getSize", "get", "put", "get", "getKeys"] [[2], ["a", 1], ["b", 2], [], ["c", 3], [], [], ["a"], ["a", 10], ["a"], []] Output: [null, null, null, 4, null, 4, 3, 1, null, 10, ["a", "b", "c"]] Explanation: ht = HashTable(2) # capacity = 2, 0 entries ht.put("a", 1) # adds ("a", 1); load = 1/2 = 0.5 ht.put("b", 2) # adds ("b", 2); load = 2/2 = 1.0 > 0.75, resize to 4 ht.getCapacity() # -> 4 (resized after second put) ht.put("c", 3) # adds ("c", 3); load = 3/4 = 0.75, no resize ht.getCapacity() # -> 4 ht.getSize() # -> 3 ht.get("a") # -> 1 ht.put("a", 10) # updates "a" to 10 (no size change) ht.get("a") # -> 10 (value was updated) ht.getKeys() # -> ["a", "b", "c"] ``` Starting from one bucket, with removals: ```text Input: ["HashTable", "put", "put", "remove", "remove", "get", "getSize", "getCapacity", "getKeys"] [[1], ["x", 5], ["y", 7], ["x"], ["x"], ["x"], [], [], []] Output: [null, null, null, true, false, -1, 1, 4, ["y"]] Explanation: ht = HashTable(1) # capacity = 1, 0 entries ht.put("x", 5) # load = 1/1 = 1.0 > 0.75, resize to 2 ht.put("y", 7) # load = 2/2 = 1.0 > 0.75, resize to 4 ht.remove("x") # -> true, size is now 1 ht.remove("x") # -> false, "x" is already gone ht.get("x") # -> -1 ht.getSize() # -> 1 ht.getCapacity() # -> 4 (resizing only happens on insertion) ht.getKeys() # -> ["y"] ``` ```hint When the load factor is checked Only a brand-new key changes the number of entries. Think about which branch of `put` can trigger a resize, and whether the comparison with 0.75 is strict. ``` ```hint What a resize has to redo A key's bucket index depends on the capacity. After the capacity doubles, ask where each existing entry now belongs and whether any of the work `put` normally does is still needed while moving entries. ``` ### Constraints & Assumptions - `1 <= capacity <= 10⁴` for the initial capacity. - Keys are non-empty strings consisting of lowercase English letters and digits. - Values are integers in the range `[-10⁵, 10⁵]`. - At most `10⁴` calls are made to `put`, `get`, `remove`, `getKeys`, `getSize`, and `getCapacity` combined. ### Clarifying Questions to Ask - May I use the language's built-in string hash function, or should I write my own? - Should the table ever shrink after removals, or does the capacity only grow? - A stored value can be -1, which is also what `get` returns for a missing key. Is that ambiguity acceptable for this interface? - Should `getKeys` sort by plain character order, so that digits come before letters? ### What a Strong Answer Covers - How a key maps to a bucket index, including keeping the index non-negative and in range. - The difference between updating and inserting in `put`, and which of the two changes the size and can trigger a resize. - A correct resize: when it fires, how every entry is placed again under the new capacity, and why doubling keeps `put` amortized O(1). - Time and space complexity of each method, including what `getKeys` costs. - Edge cases such as an initial capacity of 1, removing a key that is not present, and a stored value of -1. ### Follow-up Questions - How would you build the same table with open addressing, and how would deletion work there? - How would you shrink the table after many removals without it bouncing between two sizes? - If an attacker chooses keys that all land in one bucket, what happens to performance, and how do production hash tables defend against it? - Resizing a very large table at once causes a latency spike. How could you spread the rehash work across later operations?

Overview: Implement a string-to-integer hash table from scratch with separate chaining, insert, lookup, delete, a sorted key listing, and automatic doubling when the load factor passes 0.75. It tests bucket indexing, rehashing on resize, amortized complexity, and edge cases such as updates and removals.

PracHub logo
General
Nov 24, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design and implement a hash table from scratch that supports insertion, lookup, and deletion of key-value pairs. Keys are strings and values are integers.

The hash table should use chaining (a list of entries per bucket) as the collision resolution strategy. When the load factor (number of entries divided by number of buckets) exceeds 0.75 after an insertion, the table must automatically resize by doubling its capacity and rehashing all existing entries.

If a key already exists during insertion, its value should be updated. Lookups for missing keys return -1. Removal returns a boolean indicating whether the key was found.

Implement a class HashTable whose constructor takes the initial number of buckets, with these methods:

  • put(key: str, value: int) -> None : insert or update a key-value pair. If the load factor exceeds 0.75 after the insertion, the table resizes by doubling its capacity and rehashing all entries.
  • get(key: str) -> int : return the value associated with the key, or -1 if the key is not found.
  • remove(key: str) -> bool : remove the key-value pair for the key. Return True if the key was found and removed, False otherwise.
  • getKeys() -> List[str] : return a sorted list of all keys currently stored in the table.
  • getSize() -> int : return the number of key-value pairs currently stored.
  • getCapacity() -> int : return the current number of buckets.

Each example below is a sequence of calls on one table. The first list holds the method names, the second their arguments, and the output holds each call's return value (null for the constructor and for put).

Starting from two buckets:

Input:
["HashTable", "put",    "put",    "getCapacity", "put",    "getCapacity", "getSize", "get", "put",     "get", "getKeys"]
[[2],         ["a", 1], ["b", 2], [],            ["c", 3], [],            [],        ["a"], ["a", 10], ["a"], []]

Output: [null, null, null, 4, null, 4, 3, 1, null, 10, ["a", "b", "c"]]

Explanation:
ht = HashTable(2)                # capacity = 2, 0 entries
ht.put("a", 1)                   # adds ("a", 1); load = 1/2 = 0.5
ht.put("b", 2)                   # adds ("b", 2); load = 2/2 = 1.0 > 0.75, resize to 4
ht.getCapacity()                 # -> 4    (resized after second put)
ht.put("c", 3)                   # adds ("c", 3); load = 3/4 = 0.75, no resize
ht.getCapacity()                 # -> 4
ht.getSize()                     # -> 3
ht.get("a")                      # -> 1
ht.put("a", 10)                  # updates "a" to 10 (no size change)
ht.get("a")                      # -> 10   (value was updated)
ht.getKeys()                     # -> ["a", "b", "c"]

Starting from one bucket, with removals:

Input:
["HashTable", "put",    "put",    "remove", "remove", "get", "getSize", "getCapacity", "getKeys"]
[[1],         ["x", 5], ["y", 7], ["x"],    ["x"],    ["x"], [],        [],            []]

Output: [null, null, null, true, false, -1, 1, 4, ["y"]]

Explanation:
ht = HashTable(1)                # capacity = 1, 0 entries
ht.put("x", 5)                   # load = 1/1 = 1.0 > 0.75, resize to 2
ht.put("y", 7)                   # load = 2/2 = 1.0 > 0.75, resize to 4
ht.remove("x")                   # -> true, size is now 1
ht.remove("x")                   # -> false, "x" is already gone
ht.get("x")                      # -> -1
ht.getSize()                     # -> 1
ht.getCapacity()                 # -> 4    (resizing only happens on insertion)
ht.getKeys()                     # -> ["y"]

Constraints & Assumptions

  • 1 <= capacity <= 10⁴ for the initial capacity.
  • Keys are non-empty strings consisting of lowercase English letters and digits.
  • Values are integers in the range [-10⁵, 10⁵] .
  • At most 10⁴ calls are made to put , get , remove , getKeys , getSize , and getCapacity combined.

Clarifying Questions to Ask Guidance

  • May I use the language's built-in string hash function, or should I write my own?
  • Should the table ever shrink after removals, or does the capacity only grow?
  • A stored value can be -1, which is also what get returns for a missing key. Is that ambiguity acceptable for this interface?
  • Should getKeys sort by plain character order, so that digits come before letters?

What a Strong Answer Covers Guidance

  • How a key maps to a bucket index, including keeping the index non-negative and in range.
  • The difference between updating and inserting in put , and which of the two changes the size and can trigger a resize.
  • A correct resize: when it fires, how every entry is placed again under the new capacity, and why doubling keeps put amortized O(1).
  • Time and space complexity of each method, including what getKeys costs.
  • Edge cases such as an initial capacity of 1, removing a key that is not present, and a stored value of -1.

Follow-up Questions Guidance

  • How would you build the same table with open addressing, and how would deletion work there?
  • How would you shrink the table after many removals without it bouncing between two sizes?
  • If an attacker chooses keys that all land in one bucket, what happens to performance, and how do production hash tables defend against it?
  • Resizing a very large table at once causes a latency spike. How could you spread the rehash work across later operations?