Community Problem

Design HashMap

Difficulty: Medium

Implement a HashMap from scratch using a fixed bucket array with separate chaining; support put / get / remove on integer keys.

Design HashMap

Implement a HashMap from scratch using a fixed bucket array with separate chaining; support put / get / remove on integer keys.

MEDIUM
Free
hash-map
hash-table
linked-list
chloekelly

By @chloekelly

May 11, 2026

·

Updated May 18, 2026

312 views

2

4.3 (9)

I had this on a Reddit infrastructure phone screen as the warm-up before a system-design round. The interviewer specifically said "don't use the language's built-in map, build it." The standard production-ready answer is a fixed bucket array with separate chaining (one list per bucket), and it's worth practicing the chaining idea before you ever touch consistent hashing or open addressing.

Design HashMap

Design a HashMap without using any built-in hash table libraries.

Implement the MyHashMap class:

  • MyHashMap() initializes the object with an empty map.
  • void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value.
  • int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
  • void remove(int key) removes the key and its corresponding value if the map contains the mapping for the key.

Examples

Example 1:

MyHashMap myHashMap = new MyHashMap();
myHashMap.put(1, 1);    // map = {1=1}
myHashMap.put(2, 2);    // map = {1=1, 2=2}
myHashMap.get(1);       // returns 1
myHashMap.get(3);       // returns -1 (not found)
myHashMap.put(2, 1);    // map = {1=1, 2=1} (update existing)
myHashMap.get(2);       // returns 1
myHashMap.remove(2);    // map = {1=1}
myHashMap.get(2);       // returns -1 (now removed)

Constraints

  • 0 <= key, value <= 10^6.
  • At most 10^4 calls will be made to put, get, and remove.

Follow-up

Why a fixed-size bucket array with chaining? It is the simplest correct design and decouples bucket count from element count. With 10^4 operations and 1000 buckets, average chain length stays around 10, well below O(n) worst case.

Solution

Hints

0/3
Hint 1
Hint 2
Hint 3
All Problems