Java Design Program · CD20
Implement a HashMap from Scratch in Java
A hash map turns a key into an array index, so finding a value takes one jump instead of a search. The tricky parts are collisions and growing the array.
Problem Statement
Write MyHashMap with put(), get(), remove() and size(). It starts with 16 slots and doubles when the size exceeds 75% of the capacity.
Updating an existing key replaces its value without changing the size, and a null key is allowed.
Input/Output Examples
12 entries, capacity 16Outputcapacity 16Explanation: 12 is exactly 0.75 × 16.13th putOutputcapacity 32Explanation: 13 is more than the threshold of 12.put("key7", 777)Outputsize stays 13Explanation: the key already exists.remove("key3")Output30, then get returns nullExplanation: the entry is gone and the size drops to 12.Visual Explanation
- hash(key)mixh ^ (h >>> 16)spread the high bits
- indexslothash & (n - 1)n is a power of 2
- collisionbucket 5key2key9chain or probe
- 13 > 12capacity1632rehash every entry
- DoneO(1) average lookups
Masking with n - 1 works only because the capacity is a power of two, which is why the table always doubles.
Approaches
Both approaches pass the same 1.8 million random operations against java.util.HashMap. The first chains colliding entries; the second probes for the next free slot.
Approach 1: Separate Chaining (Recommended)
Idea: each slot holds a linked list of nodes; a new key is added to the front of its slot's list.
- Compute the mixed hash and the slot index.
- Walk the slot's list; if the key exists, replace the value.
- Otherwise add a node and resize if
size > capacity × 0.75. - When resizing, move every node to its slot in the doubled table, reusing the stored hash.
Time: O(1) average · Space: O(n). the worst case is O(n) when every key collides.
Approach 2: Open Addressing With Linear Probing
Idea: store keys and values directly in arrays; on a collision, try the next slot until the key or a free slot is found.
- Probe from the home slot until you find the key or an empty slot.
- Insert into the empty slot, or update the found one.
- On remove, shift later entries of the same run back so lookups never stop early.
- Resize by re-inserting every entry into larger arrays.
Time: O(1) average · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Separate Chaining (Recommended)
This is how java.util.HashMap works, minus its tree bins for long chains.
import java.util.Objects;
public class HashMapChaining {
// Array of buckets; each bucket is a singly linked list of entries (separate chaining)
static class MyHashMap<K, V> {
private static final class Node<K, V> {
final int hash;
final K key;
V value;
Node<K, V> next;
Node(int hash, K key, V value, Node<K, V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; }
}
private Node<K, V>[] table = newTable(16);
private int size;
@SuppressWarnings("unchecked")
private static <K, V> Node<K, V>[] newTable(int n) { return (Node<K, V>[]) new Node[n]; }
private static int hash(Object key) {
int h = Objects.hashCode(key);
return h ^ (h >>> 16); // mix high bits into the low bits used for the index
}
private int index(int hash, int length) { return hash & (length - 1); } // length is a power of 2
V put(K key, V value) {
int h = hash(key);
int i = index(h, table.length);
for (Node<K, V> n = table[i]; n != null; n = n.next) {
if (n.hash == h && Objects.equals(n.key, key)) {
V old = n.value;
n.value = value;
return old;
}
}
table[i] = new Node<>(h, key, value, table[i]);
if (++size > table.length * 3 / 4) { // load factor 0.75
resize();
}
return null;
}
V get(Object key) {
int h = hash(key);
for (Node<K, V> n = table[index(h, table.length)]; n != null; n = n.next) {
if (n.hash == h && Objects.equals(n.key, key)) return n.value;
}
return null;
}
V remove(Object key) {
int h = hash(key);
int i = index(h, table.length);
Node<K, V> prev = null;
for (Node<K, V> n = table[i]; n != null; prev = n, n = n.next) {
if (n.hash == h && Objects.equals(n.key, key)) {
if (prev == null) table[i] = n.next; else prev.next = n.next;
size--;
return n.value;
}
}
return null;
}
private void resize() {
Node<K, V>[] old = table;
table = newTable(old.length * 2);
for (Node<K, V> head : old) {
for (Node<K, V> n = head; n != null; ) {
Node<K, V> next = n.next;
int i = index(n.hash, table.length); // the stored hash avoids calling hashCode() again
n.next = table[i];
table[i] = n;
n = next;
}
}
}
int size() { return size; }
int capacity() { return table.length; }
}
public static void main(String[] args) {
MyHashMap<String, Integer> map = new MyHashMap<>();
for (int i = 1; i <= 13; i++) {
map.put("key" + i, i * 10);
if (i == 12 || i == 13) {
System.out.println("after put #" + i + ": size=" + map.size() + ", capacity=" + map.capacity());
}
}
System.out.println("get(key7) = " + map.get("key7") + ", get(key99) = " + map.get("key99"));
map.put("key7", 777); // update, not a new entry
System.out.println("after update: get(key7) = " + map.get("key7") + ", size=" + map.size());
System.out.println("remove(key3) = " + map.remove("key3") + ", get(key3) = " + map.get("key3") + ", size=" + map.size());
map.put(null, 0);
System.out.println("null key supported: " + (map.get(null) == 0));
}
}
after put #12: size=12, capacity=16 after put #13: size=13, capacity=32 get(key7) = 70, get(key99) = null after update: get(key7) = 777, size=13 remove(key3) = 30, get(key3) = null, size=12 null key supported: true
Time complexity: O(1) average · Space complexity: O(n).
Approach 2: Open Addressing With Linear Probing
No node objects and good cache locality, but deletion needs care and performance drops quickly at high load.
import java.util.Objects;
public class HashMapLinearProbing {
// Open addressing: entries live directly in the arrays; a collision moves on to the next free slot
static class MyHashMap<K, V> {
private Object[] keys = new Object[16];
private Object[] values = new Object[16];
private boolean[] used = new boolean[16];
private int size;
private static int hash(Object key) {
int h = Objects.hashCode(key);
return h ^ (h >>> 16);
}
private int slotOf(Object key) { // the slot holding key, or the free slot where it would go
int mask = keys.length - 1;
int i = hash(key) & mask;
while (used[i] && !Objects.equals(keys[i], key)) {
i = (i + 1) & mask;
}
return i;
}
@SuppressWarnings("unchecked")
V put(K key, V value) {
int i = slotOf(key);
if (used[i]) {
V old = (V) values[i];
values[i] = value;
return old;
}
used[i] = true;
keys[i] = key;
values[i] = value;
if (++size > keys.length * 3 / 4) { // the same 0.75 load factor
resize();
}
return null;
}
@SuppressWarnings("unchecked")
V get(Object key) {
int i = slotOf(key);
return used[i] ? (V) values[i] : null;
}
// Backward-shift deletion: move later entries of the same run back so lookups never stop early
@SuppressWarnings("unchecked")
V remove(Object key) {
int i = slotOf(key);
if (!used[i]) return null;
V old = (V) values[i];
int mask = keys.length - 1;
int gap = i;
int j = (i + 1) & mask;
while (used[j]) {
int home = hash(keys[j]) & mask;
// entry j may move into the gap only if its home slot is not between gap (exclusive) and j
boolean canMove = gap <= j ? (home <= gap || home > j) : (home <= gap && home > j);
if (canMove) {
keys[gap] = keys[j];
values[gap] = values[j];
gap = j;
}
j = (j + 1) & mask;
}
used[gap] = false;
keys[gap] = null;
values[gap] = null;
size--;
return old;
}
@SuppressWarnings("unchecked")
private void resize() {
Object[] oldKeys = keys, oldValues = values;
boolean[] oldUsed = used;
keys = new Object[oldKeys.length * 2];
values = new Object[oldKeys.length * 2];
used = new boolean[oldKeys.length * 2];
size = 0;
for (int i = 0; i < oldKeys.length; i++) {
if (oldUsed[i]) put((K) oldKeys[i], (V) oldValues[i]);
}
}
int size() { return size; }
int capacity() { return keys.length; }
}
public static void main(String[] args) {
MyHashMap<String, Integer> map = new MyHashMap<>();
for (int i = 1; i <= 13; i++) {
map.put("key" + i, i * 10);
if (i == 12 || i == 13) {
System.out.println("after put #" + i + ": size=" + map.size() + ", capacity=" + map.capacity());
}
}
System.out.println("get(key7) = " + map.get("key7") + ", get(key99) = " + map.get("key99"));
map.put("key7", 777); // update, not a new entry
System.out.println("after update: get(key7) = " + map.get("key7") + ", size=" + map.size());
System.out.println("remove(key3) = " + map.remove("key3") + ", get(key3) = " + map.get("key3") + ", size=" + map.size());
map.put(null, 0);
System.out.println("null key supported: " + (map.get(null) == 0));
}
}
after put #12: size=12, capacity=16 after put #13: size=13, capacity=32 get(key7) = 70, get(key99) = null after update: get(key7) = 777, size=13 remove(key3) = 30, get(key3) = null, size=12 null key supported: true
Time complexity: O(1) average · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Separate Chaining | O(1) average | O(n) |
| Open Addressing With Linear Probing | O(1) average | O(n) |
With a good hash and a load factor of 0.75, each operation inspects only a few entries on average. A resize costs O(n), but it happens rarely enough that inserts stay O(1) amortised.
Interview Tips and Recommended Approach
- Explain the threshold: capacity × load factor, so 16 × 0.75 = 12 entries before the first resize.
- Use
equals()after comparing hashes. Equal hashes do not mean equal keys. - Mention Java 8 tree bins.
HashMapturns a chain of 8 or more into a red-black tree when the table has at least 64 slots. - Keys must not change after insertion, or their hash no longer matches their slot.
Recommended Approach: Separate Chaining
Why: it is the design java.util.HashMap uses, removal is trivial and it degrades gracefully when the table fills up.