Scrivio Interview library
Designing data structuresDesigning data structuresReported 17 times · 17 min read · updated 15 November 2026

Design and implement your own hash map.

1What our own hash map has to do

Think of the post room in a large hostel. On the wall is a grid of numbered pigeonholes. When a letter arrives, the porter does not search the whole room for the right place. He applies a fixed rule to the name on the envelope, say the last digit of the room number, and drops the letter into that pigeonhole. When a student asks for their post, the porter applies the same rule and looks in just one pigeonhole. A hash map is that post room, and it is far smaller an idea than it sounds.

Let us be clear about what a map does before we build one. A map stores pairs, each made of a key and a value, and each key appears at most once. put(key, value) stores a pair; if the key is already there, it replaces the old value and returns it. get(key) returns the value stored with the key, or null if the key is not there. remove(key) deletes the pair and returns its value.

Now a small example by hand, the one we will use throughout. We put ana with 31, bo with 25, cy with 40 and di with 19. get(bo) gives 25. put(bo, 26) replaces the value and gives back the old 25, so get(bo) now gives 26. remove(ana) gives 31, and after that get(ana) gives null. get(zed) gives null too, because zed was never stored.

PictureThe pairs our map will hold

Top row: the keys. Bottom row: the value stored with each key.

  1. anabocydi31254019
    get(bo)
    25
    get(zed)
    null

    1We will store four pairs: ana with 31, bo with 25, cy with 40 and di with 19. Each key may appear only once.

What to assume

What types are the keys?
We assume any object with a sensible equals and hashCode, so the map is generic.
May a key be null?
Yes, once, as java.util.HashMap allows.
How many entries?
No fixed limit, so the map must grow.
Is it used by several threads?
No, one thread.
And what cost is expected?
O(1) on average for put, get and remove, which means a fixed amount of work however many pairs we hold.

A careful candidate asks a few things before writing code. What types are the keys? We assume any object with a sensible equals and hashCode, so the map is generic. May a key be null? Yes, once, as java.util.HashMap allows. How many entries? No fixed limit, so the map must grow. Is it used by several threads? No, one thread. And what cost is expected? O(1) on average for put, get and remove, which means a fixed amount of work however many pairs we hold.

2How to spot a design question and what it asks for

On a first reading, the words design and implement your own can be frightening. There is no input array and no output to compute, and a beginner may wonder where to even begin, or be tempted to wrap java.util.HashMap, which misses the point. The way in is to read the question as a list of jobs and ask, for each job, what it costs.

The first clue is the word design. A design question gives us an interface, a handful of operations, and a target cost for each, rather than one input and one answer. That tells us we are choosing building blocks, an array, a list, a few counters, and the rules that keep them consistent after every operation.

The second clue is the word map. Every operation, put, get and remove, begins with the same step: find this key. So the whole design depends on making that one step fast. The general advice for design questions is to pick the cheapest structure for the most frequent step.

The third clue is the word hash. The only structure that finds something in constant time is an array, because reading slot 7 costs the same as reading slot 0. So we need a way to turn any key into a slot number. That conversion is what a hash function does, and it is where the name comes from.

These clues place the problem in the designing data structures pattern, where we combine simple parts so that each operation meets its cost. The rule to carry to new problems is to list the operations, find the step they all share, and choose parts that make that step cheap; then write down the facts the parts must always keep true. LRU caches, sets and frequency counters are all designed the same way.

Some designs look similar but fit less well. A balanced search tree, like java.util.TreeMap, keeps keys sorted, which we did not ask for, at O(log n) per operation. A direct-address array, one slot for every possible key, is perfect for small integer keys but impossible for strings, because there are far too many possible strings.

3The honest first attempt, one list of every pair

The first design anyone would write keeps every pair in one ArrayList. To put, we walk the list looking for the key; if we find it we replace the value, and otherwise we add a new pair at the end. To get, we walk the list until we meet the key, and return null if we reach the end. It is short and correct, a brute force in the good sense: the plain approach with no cleverness, and a perfectly good place to start.

By hand, after our four puts the list reads ana, bo, cy, di. get(di) compares di with ana, bo and cy before it finds di, four comparisons. get(zed) compares zed with all four and only then returns null.

Java
record Entry(String key, int value) {}
static List<Entry> entries = new ArrayList<>();
static void put(String key, int value) {
for (int i = 0; i < entries.size(); i++) {
if (entries.get(i).key().equals(key)) { entries.set(i, new Entry(key, value)); return; }
}
entries.add(new Entry(key, value)); // a new key goes at the end
}
static Integer get(String key) {
for (Entry e : entries) if (e.key().equals(key)) return e.value();
return null; // we compared every key
}

Now let us count. With n pairs in the list, a get for a missing key makes n comparisons, and every put must make the same walk before it can add, so each operation is O(n). Building a map of n pairs one put at a time costs about 1 + 2 + ... + n comparisons, which grows like n times n, O(n^2).

So where is the waste? When we look for zed, we compare it with ana, bo, cy and di, keys that had no chance of being zed. In the post room, that would be the porter reading every letter in the building to find one student's post. If we could split the pairs into many small groups and know, from the key alone, which group it must be in, we would look in only that one group.

4From one long list to buckets, chains and resizing

The groups are the pigeonholes, which we call buckets: an array of, say, 4 buckets. Every Java object has a method hashCode that turns it into an int, and for a String it is worked out from the characters. For bo, the letter b is 98 and o is 111, and the hash code is 98 times 31 plus 111, which is 3149. The one promise that matters is that equal keys always have equal hash codes. So a key can only ever live in the bucket its hash code points to, and every other bucket can be skipped.

Next we must turn a hash code like 3149 into a bucket number between 0 and 3. If the number of buckets is a power of two, such as 4, 8 or 16, this is a cheap step. The operator & compares two numbers bit by bit in binary and keeps a 1 only where both have one, so h & (capacity - 1) keeps only the lowest bits of h. With 4 buckets the mask is 3, binary 11, so we keep the last two bits. 3190, the hash code of cy, ends in the bits 10 in binary, so cy goes into bucket 2.

A beginner rightly asks what happens when two different keys land in the same bucket. It is bound to happen, because there are many more keys than buckets, and it is called a collision. In our example, ana and bo both land in bucket 1. We handle it with chaining: each bucket holds the start, called the head, of a small linked list of nodes, and a new key is added at the head. Inside a chain we compare keys with equals, never by hash code alone, because different keys can share a hash code; the strings Aa and BB both have hash code 2112.

There is one small trap in the masking step. It keeps only the low bits, so two hash codes that differ only in their high bits would always collide. So before masking we fold the high bits into the low ones with h ^ (h >>> 16), which moves the top sixteen bits down and mixes them in. For ana, 96724 has a 1 in its high part, and mixing turns it into 96725.

Chains only help while they stay short. The load factor, the number of entries divided by the number of buckets, is the average chain length. With 4 buckets and a million entries we would be back to long lists. So when the size passes three quarters of the capacity, we double the array and place every entry again. Why again? Because a key's bucket depends on the capacity: ana is in bucket 1 of 4 but bucket 5 of 8.

Is resizing not expensive? One resize costs O(n), since every entry moves. But the array doubles, so the next resize comes only after the map has grown by as many entries as it already held. Spread over all the puts, the cost per put stays O(1). This is called amortised cost: one slow call, paid for by many fast ones. In the post room, the porter occasionally builds a bigger wall and re-sorts every letter, but most days he just drops letters into place.

5Watching the buckets through the example

The picture follows our example on the real code, starting from 4 buckets. Each row is one bucket, labelled by its index in the first box, and the keys after it are that bucket's chain, from the head on the left. The panel shows each key's hash code and bucket, the size and capacity, and the values stored.

Watch for three moments in particular. The first is the collision in bucket 1, the second is the resize when the fourth key arrives, and the third is how get looks at only one bucket.

Step throughBuckets and chains through the example

Each row is one bucket, labelled by its index in the first box. The keys after it are that bucket's chain, from its head on the left.

  1. [0][1][2][3]
    operation
    new MyHashMap()
    size, capacity
    0, 4
    entries
    none

    1A new map is an array of 4 empty buckets and size = 0. Each row is one bucket; its first box is the bucket's index.

  2. [0][1]ana[2][3]
    operation
    put(ana, 31)
    hash, bucket
    96724, 1 of 4
    size, capacity
    1, 4
    entries
    ana=31

    2put(ana, 31): the hash of ana, mixed and masked with 3, gives bucket 1. The bucket is empty, so ana becomes its first node.

  3. [0][1]boana[2][3]
    operation
    put(bo, 25)
    hash, bucket
    3149, 1 of 4
    size, capacity
    2, 4
    entries
    bo=25 ana=31

    3put(bo, 25) also lands in bucket 1, a collision. We compare bo with ana using equals, find no match, and add bo at the head of the chain.

  4. [0][1]boana[2]cy[3]
    operation
    put(cy, 40)
    hash, bucket
    3190, 2 of 4
    size, capacity
    3, 4
    entries
    bo=25 ana=31 cy=40

    4put(cy, 40) lands in bucket 2, which is empty, so cy simply becomes its first node. size is now 3.

  5. [0][1]diboana[2]cy[3]
    operation
    put(di, 19)
    hash, bucket
    3205, 1 of 4
    4 > 4 * 3 / 4
    yes, resize
    size, capacity
    4, 4
    entries
    di=19 bo=25 ana=31 cy=40

    5put(di, 19) lands in bucket 1 and goes at the head of its chain. size becomes 4, more than 3 of 4 buckets, so a resize starts.

  6. [0][1][2][3][4][5]anabodi[6]cy[7]
    operation
    resize to 8
    new buckets
    ana, bo, di: 5; cy: 6
    size, capacity
    4, 8
    entries
    ana=31 bo=25 di=19 cy=40

    6The resize makes 8 buckets and places every node again by its new index. ana, bo and di all move to bucket 5, and cy moves to 6.

  7. [0][1][2][3][4][5]anabodi[6]cy[7]
    operation
    get(bo)
    returns
    25
    size, capacity
    4, 8
    entries
    ana=31 bo=25 di=19 cy=40

    7get(bo) goes to bucket 5 of 8. It compares ana, which is not equal, then bo, which is, and returns 25. Other buckets are never looked at.

  8. [0][1][2][3][4][5]anabodi[6]cy[7]
    operation
    put(bo, 26)
    returns
    25, the old value
    size, capacity
    4, 8
    entries
    ana=31 bo=26 di=19 cy=40

    8put(bo, 26) finds bo already in bucket 5, so it replaces the value and returns the old one, 25. size does not change.

  9. [0][1][2][3][4][5]bodi[6]cy[7]
    operation
    remove(ana)
    returns
    31
    size, capacity
    3, 8
    entries
    bo=26 di=19 cy=40

    9remove(ana) finds ana at the head of bucket 5's chain, so the bucket now starts at bo. It returns 31 and size drops to 3.

  10. [0][1][2][3][4][5]bodi[6]cy[7]
    operation
    get(ana), get(zed)
    returns
    null, null
    size, capacity
    3, 8
    entries
    bo=26 di=19 cy=40

    10get(ana) now finds bo and di in bucket 5, neither equal, and returns null. get(zed) lands in empty bucket 0 and returns null at once.

  11. [0]null[1][2][3][4][5]bodi[6]cy[7]
    operation
    put(null, 0)
    hash, bucket
    0, 0 of 8
    size, capacity
    4, 8
    entries
    null=0 bo=26 di=19 cy=40

    11put(null, 0): a null key is given hash 0, so it goes into bucket 0. It is stored like any other key, and size is 4 again.

Let us read those moments back. In the third frame bo collides with ana in bucket 1. put compares bo with ana using equals, finds them different, and puts bo at the head, so the chain reads bo, ana. In the fifth frame di joins the same chain and size becomes 4, which is more than 4 times 3 divided by 4, that is 3, so the resize begins.

In the sixth frame the array has 8 buckets. With the mask now 7, binary 111, we keep three bits, and ana, bo and di all land in bucket 5 while cy moves to bucket 6. The resize walks the old chain di, bo, ana and adds each at the head of its new bucket, so the new chain reads ana, bo, di. The order inside a chain never matters.

From then on, every get visits only one bucket. get(bo) compares two keys out of four. get(zed) lands in bucket 0, which is empty, and returns null without comparing anything at all.

6The complete Java program

Here is the full class. It is generic and uses Objects.equals so that a null key compares safely. It starts with 4 buckets only so that main can show a resize; a real map would start with 16.

Java
import java.util.Objects;
public class MyHashMap<K, V> {
private static final class Node<K, V> {
final K key; V value; Node<K, V> next;
Node(K key, V value, Node<K, V> next) { this.key = key; this.value = value; this.next = next; }
}
private Node<K, V>[] buckets;
private int size;
@SuppressWarnings("unchecked")
public MyHashMap() { buckets = (Node<K, V>[]) new Node[4]; } // small, to show resizing
private int indexFor(Object key, int length) {
int h = (key == null) ? 0 : key.hashCode();
h ^= (h >>> 16); // mix high bits into the low bits we keep
return h & (length - 1); // length is a power of two, so this is h mod length
}
public V put(K key, V value) {
int i = indexFor(key, buckets.length);
for (Node<K, V> n = buckets[i]; n != null; n = n.next) {
if (Objects.equals(n.key, key)) { V old = n.value; n.value = value; return old; }
}
buckets[i] = new Node<>(key, value, buckets[i]); // new key: add at the head of the chain
if (++size > buckets.length * 3 / 4) resize(); // keep the load factor at most 0.75
return null;
}
public V get(K key) {
for (Node<K, V> n = buckets[indexFor(key, buckets.length)]; n != null; n = n.next) {
if (Objects.equals(n.key, key)) return n.value;
}
return null;
}
public V remove(K key) {
int i = indexFor(key, buckets.length);
Node<K, V> prev = null;
for (Node<K, V> n = buckets[i]; n != null; prev = n, n = n.next) {
if (Objects.equals(n.key, key)) {
if (prev == null) buckets[i] = n.next; else prev.next = n.next; // unlink
size--;
return n.value;
}
}
return null;
}
@SuppressWarnings("unchecked")
private void resize() {
Node<K, V>[] old = buckets;
buckets = (Node<K, V>[]) new Node[old.length * 2];
for (Node<K, V> head : old) {
for (Node<K, V> n = head; n != null; n = n.next) {
int i = indexFor(n.key, buckets.length); // the index depends on the length
buckets[i] = new Node<>(n.key, n.value, buckets[i]);
}
}
}
public int size() { return size; }
int capacity() { return buckets.length; }
public static void main(String[] args) {
MyHashMap<String, Integer> ages = new MyHashMap<>();
ages.put("ana", 31); ages.put("bo", 25); ages.put("cy", 40);
System.out.println(ages.capacity()); // 4
ages.put("di", 19); // 4 > 3 entries: it doubles
System.out.println(ages.capacity()); // 8
System.out.println(ages.get("bo")); // 25
System.out.println(ages.put("bo", 26)); // 25
System.out.println(ages.get("bo")); // 26
System.out.println(ages.remove("ana")); // 31
System.out.println(ages.get("ana")); // null
System.out.println(ages.get("zed")); // null
ages.put(null, 0);
System.out.println(ages.get(null) + " " + ages.size()); // 0 4
}
}

Let us read it in the order a put runs. indexFor first takes the key's hash code, using 0 for a null key. Then h ^= (h >>> 16) mixes the high bits into the low bits, and h & (length - 1) keeps the low bits as the bucket index. This works only because the length is always a power of two.

put then walks the chain in that bucket. If Objects.equals finds the key, it swaps in the new value and returns the old one, and the size is unchanged. If the walk reaches the end, the key is new: new Node<>(key, value, buckets[i]) makes a node whose next is the old head, and that node becomes the new head. Then ++size > buckets.length * 3 / 4 checks the load factor and calls resize when it is exceeded.

get computes the same index and walks the same chain, returning the value on a match and null at the end. remove walks the chain with two references, prev one step behind n. When it finds the key, it unlinks the node: if the node is the head, the bucket itself now starts at the next node; otherwise prev.next skips over it. The size goes down by one.

resize makes an array twice as long and walks every chain of the old array, placing each key again by indexFor with the new length, because the index depends on it. main prints the capacity before and after the fourth put, then the results we worked by hand, and finally 0 4, the value for the null key and the size.

7How much it costs, and the cases at the edges

Let us count on the example first. Each operation computed one index and looked at one bucket. The longest chain we ever walked had three nodes, and get(zed) walked none. With a hash function that spreads keys evenly, the average chain length is the load factor, which we keep at or below 0.75, so put, get and remove do O(1) work on average.

The worst case is different. If every key had the same hash code, for instance from a badly written hashCode that returns a constant, every key would share one chain and each operation would be O(n), no better than the list. A single put that triggers a resize is also O(n), but amortised over all puts it is O(1). The space is O(n): one node per entry, plus an array whose length stays within a small multiple of n.

Comparing the designs
Designput, get, removeSpaceNotes
One list of pairsO(n)O(n)compares every key
Direct-address arrayO(1)O(range of keys)only small integer keys
Buckets, chains and resizingO(1) average, O(n) worstO(n)any keys

The edge cases are handled by the code above. A null key hashes to 0 and is compared with Objects.equals, so it behaves like any other key. Putting an existing key replaces its value and does not change the size. Getting or removing a missing key returns null, and removing the head of a chain updates the bucket itself.

The mistake beginners most often make is to compare keys by hash code instead of equals, which mixes up Aa and BB. The second is to forget that a null result cannot tell a missing key from a key stored with the value null, which is why the real API also has containsKey.

8Follow-up questions

How does Java's HashMap protect itself against very long chains?

Since Java 8, when one bucket's chain grows beyond eight nodes and the table has at least 64 buckets, java.util.HashMap turns that chain into a small red-black tree, a search tree that keeps itself balanced. Looking up a key in that bucket then takes O(log k) steps for k colliding keys, instead of walking all k of them. Maps with decent hash codes almost never build these trees; they are a guard against bad or hostile keys.

What happens if a key's hashCode changes after we insert it?

The node stays in the bucket chosen by the old hash code. A later get computes the new hash code, looks in a different bucket, and does not find it, so the entry seems to vanish although it is still inside the map. That is why keys should be immutable, like String and Integer, or at least why the fields used by equals and hashCode must never change while the object is a key.

What is open addressing, and when would you choose it instead of chaining?

Open addressing stores the pairs directly in the array, with no chains. On a collision, we probe the next slots in a fixed order, for example slot i + 1, then i + 2, until we find the key or an empty slot. It uses less memory and reads neighbouring slots, which the processor does quickly. But removal is harder, because an emptied slot could break the probe path for keys stored after it, so we must mark removed slots with a special marker. It also needs a lower load factor to stay fast.

9Conclusion

We built a hash map from an array of buckets: the key's hashCode, mixed and masked, picks one bucket, keys that collide share a short chain compared with equals, and the array doubles when entries pass three quarters of the buckets. That gives O(1) average put, get and remove, O(n) in the worst case, and O(n) space. The clue to remember is a design question where every operation starts with find this key: turn the key into an array index and keep the groups small.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm the requirements: generic keys and values, put returns the old value, get and remove return null for a missing key, one null key allowed, single-threaded, and average O(1).

Then, if they want more

A single list of pairs works but every operation scans all n keys, so it is O(n). Instead I keep an array of buckets whose length is a power of two.

To find a key's bucket I take hashCode, mix the high bits into the low bits with h xor h shifted right by sixteen, and mask with length minus one. Equal keys have equal hash codes, so a key can only be in that bucket.

Collisions are handled by chaining: each bucket is a small linked list, and inside it I compare keys with equals, never by hash alone. put replaces the value if the key is in the chain, otherwise it adds a node at the head. remove unlinks the node, updating the bucket if it was the head.

When size exceeds three quarters of the capacity I double the array and rehash every entry, because the index depends on the length. That keeps chains short: O(1) average, amortised for resizes, O(n) worst case if all keys collide, and O(n) space.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 17 times in that collection. How it is counted
Official documentation
java.util, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Design and implement your own hash map.": https://scrivio-interview-library.netlify.app/data-structures/solutions/design-and-implement-your-own-hash-map-517be2/