Design HashMap
Easy
Topics
Design a HashMap without using any built-in hash table libraries. Implement MyHashMap with put(key, value), get(key) (returns the value or -1 if the key is absent), and remove(key).
Example 1
Two details carry the contract:
put on an existing key overwrites rather than appends, and get on a missing key returns -1 instead of failing.Calls run top to bottom; the arrow shows what each one returns.
Input: operations = ["MyHashMap","put","put","get","get","put","get","remove","get"], values = [[],[1,1],[2,2],[1],[3],[2,1],[2],[2],[2]] Output: [null,null,null,1,-1,null,1,null,-1]
Constraints
- 0 <= key, value <= 10^6
- At most 10^4 calls to put, get, and remove.
Editorial — intuition, approach, complexity and pitfalls
Intuition
A hash map maps keys to values with O(1) average access. Bucket keys by a hash and store (key, value) pairs so collisions live in the same bucket and are scanned linearly.
Approach
- Keep an array of buckets; hash the key to pick a bucket.
- put scans the bucket to update an existing key or appends a new pair.
- get scans the bucket and returns the value or -1; remove deletes the pair.
Dry Run
MyHashMap() -- 1009 buckets, so the index is key % 1009
put 1 1 -> null bucket 1: [[1, 1]]
put 2 2 -> null bucket 1: [[1, 1]] bucket 2: [[2, 2]]
get 1 -> 1 scan bucket 1, find key 1
get 3 -> -1 bucket 3 is empty; MISSING is -1, not 0
put 2 1 -> null bucket 2: [[2, 1]] the pair is updated in place
get 2 -> 1
remove 2 -> null bucket 2: []
get 2 -> -1
answer null|null|null|1|-1|null|1|null|-1
The row to look at is "put 2 1". The bucket still holds one pair, not two: put
scans for the key first and overwrites p[1] when it finds it. Drop that scan and
just append, and bucket 2 becomes [[2, 2], [2, 1]] -- then get(2) returns 2,
because it stops at the first match, which is the STALE one. The overwrite is
correctness, not housekeeping.
Collisions are not hypothetical, they are the normal case, and they are handled by
the linear scan rather than by any probing:
put 1 and put 1010 1010 % 1009 = 1, so both land in bucket 1
bucket 1 = [[1, 'a'], [1010, 'b']]
get(1) = 'a' get(1010) = 'b'
That is also why the stored element is a (key, value) pair and not just a value.
Without the key alongside it, nothing in a shared bucket could tell the two
entries apart.
Returning -1 for a missing key is only safe because this problem says values are
non-negative. In a real map you would return an absent-marker instead, since -1
is otherwise a legitimate value.Complexity
- Time — O(1) average: each operation touches one bucket; with a good load factor buckets stay short.
- Space — O(n): stored key/value pairs plus the bucket array.
Common Pitfalls
- get must return -1 for missing keys, not 0.
- put must overwrite an existing key rather than adding a duplicate.
Full Solution — all languages
class MyHashMap:
def __init__(self):
self.n = 1009
self.buckets = [[] for _ in range(self.n)]
def put(self, key, value):
b = self.buckets[key % self.n]
for p in b:
if p[0] == key:
p[1] = value
return
b.append([key, value])
def get(self, key):
for p in self.buckets[key % self.n]:
if p[0] == key:
return p[1]
return -1
def remove(self, key):
b = self.buckets[key % self.n]
for i in range(len(b)):
if b[i][0] == key:
b.pop(i)
returnimport java.util.*;
class MyHashMap {
static final int N = 1009;
List<int[]>[] buckets;
public MyHashMap() {
buckets = new List[N];
for (int i = 0; i < N; i++) buckets[i] = new ArrayList<>();
}
public void put(int key, int value) {
List<int[]> b = buckets[key % N];
for (int[] p : b) if (p[0] == key) {
p[1] = value;
return;
}
b.add(new int[]{key, value});
}
public int get(int key) {
for (int[] p : buckets[key % N]) if (p[0] == key) return p[1];
return -1;
}
public void remove(int key) {
List<int[]> b = buckets[key % N];
for (int i = 0; i < b.size(); i++) if (b.get(i)[0] == key) {
b.remove(i);
return;
}
}
}#include <bits/stdc++.h>
using namespace std;
class MyHashMap {
static const int N = 1009;
vector<vector<pair<int,int>>> buckets;
public: MyHashMap() : buckets(N) {
}
void put(int key, int value) {
auto& b = buckets[key % N];
for (auto& p : b) if (p.first == key) {
p.second = value;
return;
}
b.push_back({key, value});
}
int get(int key) {
for (auto& p : buckets[key % N]) if (p.first == key) return p.second;
return -1;
}
void remove(int key) {
auto& b = buckets[key % N];
for (size_t i = 0; i < b.size(); i++) if (b[i].first == key) {
b.erase(b.begin() + i);
return;
}
}
};class MyHashMap {
constructor() {
this.n = 1009;
this.buckets = Array.from({ length: this.n }, () => []);
}
put(key, value) {
const b = this.buckets[key % this.n];
for (const p of b) if (p[0] === key) {
p[1] = value;
return;
}
b.push([key, value]);
}
get(key) {
for (const p of this.buckets[key % this.n]) if (p[0] === key) return p[1];
return -1;
}
remove(key) {
const b = this.buckets[key % this.n];
for (let i = 0; i < b.length; i++) if (b[i][0] === key) {
b.splice(i, 1);
return;
}
}
}