Design HashMap

Implement a hash map from scratch using array buckets with chaining.

Easy
Time O(1) avg Space O(N + B)
LeetCode
5 min read
hash-map design

Problem#

Design a MyHashMap without using any built-in hash table:

  • put(key, value) — insert/overwrite.
  • get(key) — return value or -1.
  • remove(key) — delete the mapping.

Examples#

  • put(1, 1); put(2, 2); get(1)1; get(3)-1; put(2, 1); get(2)1; remove(2); get(2)-1.

Constraints#

  • 0 <= key, value <= 10^6, up to 10^4 calls.

Hints#

Hint
Array of B buckets, each a list of (key, value) pairs. Hash with key % B.

Approach#

Fixed-size bucket array (1024 works well here). Each bucket is a list<pair<int,int>>. put scans the bucket and updates or appends; get and remove scan and act.

Solution#

Design HashMap
class MyHashMap {
static const int B = 1024;
vector<list<pair<int,int>>> table;
int hash(int k) const { return k % B; }
public:
MyHashMap() : table(B) {}
void put(int key, int value) {
auto& bkt = table[hash(key)];
for (auto& p : bkt) if (p.first == key) { p.second = value; return; }
bkt.emplace_back(key, value);
}
int get(int key) {
auto& bkt = table[hash(key)];
for (auto& p : bkt) if (p.first == key) return p.second;
return -1;
}
void remove(int key) {
auto& bkt = table[hash(key)];
for (auto it = bkt.begin(); it != bkt.end(); ++it) {
if (it->first == key) { bkt.erase(it); return; }
}
}
};

Editorial#

Separate chaining: collisions stay in the bucket list, lookups scan the chain. With B = 1024 and up to 10^4 keys uniformly distributed, average chain length is ~10 — operations are effectively O(1). Doubling-on-load would be needed for production, but the problem’s cap makes it unnecessary.

Complexity#

  • Time: O(1) average, O(N / B) worst per op.
  • Space: O(N + B).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.