Tech Interview RoomStudy guides

Design & LLD

Implement a simplified HashMap from scratch.

Advanced · 2 min read · Lesson 2 of 3 in Design & LLD

Problem

Implement put, get and remove for a generic hash map with separate chaining and resizing, explaining design choices the way java.util.HashMap does.

java
import java.util.Objects;

class SimpleHashMap<K, V> {
    private static final class Entry<K, V> {
        final K key;
        final int hash;
        V value;
        Entry<K, V> next;
        Entry(K key, int hash, V value, Entry<K, V> next) { this.key = key; this.hash = hash; this.value = value; this.next = next; }
    }

    private static final float LOAD_FACTOR = 0.75f;
    private Entry<K, V>[] table;
    private int size;

    @SuppressWarnings("unchecked")
    SimpleHashMap() { table = (Entry<K, V>[]) new Entry[16]; }

    private static int hash(Object key) {
        int h = Objects.hashCode(key);       // null key hashes to 0
        return h ^ (h >>> 16);               // spread high bits into the low bits used for indexing
    }

    private int index(int hash, int length) { return hash & (length - 1); }   // length is a power of two

    public V put(K key, V value) {
        int h = hash(key);
        int i = index(h, table.length);
        for (Entry<K, V> e = table[i]; e != null; e = e.next) {
            if (e.hash == h && Objects.equals(e.key, key)) {
                V old = e.value;
                e.value = value;
                return old;
            }
        }
        table[i] = new Entry<>(key, h, value, table[i]);
        if (++size > table.length * LOAD_FACTOR) resize();
        return null;
    }

    public V get(Object key) {
        int h = hash(key);
        for (Entry<K, V> e = table[index(h, table.length)]; e != null; e = e.next) {
            if (e.hash == h && Objects.equals(e.key, key)) return e.value;
        }
        return null;
    }

    public V remove(Object key) {
        int h = hash(key);
        int i = index(h, table.length);
        Entry<K, V> prev = null;
        for (Entry<K, V> e = table[i]; e != null; prev = e, e = e.next) {
            if (e.hash == h && Objects.equals(e.key, key)) {
                if (prev == null) table[i] = e.next; else prev.next = e.next;
                size--;
                return e.value;
            }
        }
        return null;
    }

    public int size() { return size; }

    @SuppressWarnings("unchecked")
    private void resize() {
        Entry<K, V>[] old = table;
        table = (Entry<K, V>[]) new Entry[old.length * 2];
        for (Entry<K, V> head : old) {
            for (Entry<K, V> e = head; e != null; ) {
                Entry<K, V> next = e.next;
                int i = index(e.hash, table.length);   // reuse the cached hash
                e.next = table[i];
                table[i] = e;
                e = next;
            }
        }
    }

    public static void main(String[] args) {
        SimpleHashMap<String, Integer> m = new SimpleHashMap<>();
        for (int i = 0; i < 100; i++) m.put("k" + i, i);
        m.put(null, -1);
        System.out.println(m.get("k42") + " " + m.get(null) + " " + m.size());  // 42 -1 101
        m.remove("k42");
        System.out.println(m.get("k42") + " " + m.size());                      // null 100
    }
}

Design choices to explain

  • Separate chaining with linked lists (Java 8 also converts long chains to red-black trees); open addressing (linear probing) is more cache-friendly but needs tombstones for deletes and a lower load factor.
  • Power-of-two capacity so the index is a bitmask, plus hash spreading.
  • Load factor 0.75 balances memory against chain length.
  • Cache the hash in each entry to speed up comparisons and resizing.
  • Null key support via Objects.hashCode/Objects.equals.

Complexity

Average O(1) per operation; resizing is O(n) but amortised O(1) per insert.

Follow-up questions interviewers ask

Try answering each one before you open it.

How would you make this map thread-safe with good concurrency?

Wrapping every method in synchronized works but serialises everything. Better: lock striping (an array of locks, one per group of buckets, as Java 7's ConcurrentHashMap segments did), or the Java 8 approach: CAS to insert into an empty bucket, synchronized on the bucket's head node otherwise, volatile reads for get, and cooperative resizing. In practice, use ConcurrentHashMap.