Design HashMap

Easyhash-tabledesign
Category: System Design
Companies that ask this question:
AmazonGoogle

Approach

Design HashMap

Approach

Use array of buckets storing key-value pairs with chaining.

Algorithm

  1. Hash function: key % size
  2. Put: Hash key, update if exists, else append
  3. Get: Hash key, search bucket for key
  4. Remove: Hash key, remove from bucket

Complexity

  • Time: O(n/k) average where k is bucket count
  • Space: O(k + m) where m is number of entries

Key Insights

  • Each bucket stores list of (key, value) pairs
  • Chaining handles hash collisions
  • Update existing keys in place

Solution

java
1class MyHashMap {
2    private class Pair {
3        int key, value;
4        Pair(int key, int value) {
5            this.key = key;
6            this.value = value;
7        }
8    }
9    
10    private List<Pair>[] buckets;
11    private int size = 1000;
12    
13    public MyHashMap() {
14        buckets = new List[size];
15        for (int i = 0; i < size; i++) {
16            buckets[i] = new ArrayList<>();
17        }
18    }
19    
20    private int hash(int key) {
21        return key % size;
22    }
23    
24    public void put(int key, int value) {
25        int idx = hash(key);
26        for (Pair p : buckets[idx]) {
27            if (p.key == key) {
28                p.value = value;
29                return;
30            }
31        }
32        buckets[idx].add(new Pair(key, value));
33    }
34    
35    public int get(int key) {
36        int idx = hash(key);
37        for (Pair p : buckets[idx]) {
38            if (p.key == key) return p.value;
39        }
40        return -1;
41    }
42    
43    public void remove(int key) {
44        int idx = hash(key);
45        buckets[idx].removeIf(p -> p.key == key);
46    }
47}
Loading visualizer...