Back to solutions
Design HashMap
EasyArraysImplement a key-value map supporting put, get, remove.
Constraints
- 0 <= key, value <= 10^6
- 1 <= q <= 10^4
Direct-address array
Time O(1) per operationSpace O(max key)
Keys are bounded by 10^6, so allocate an int array of that size initialised to -1 (the 'absent' marker). put writes the value at index key, get reads it, and remove resets it to -1. Each operation is O(1).
Key terms
- sentinel value:
- A reserved value (-1 here) that means 'no entry'.
- direct addressing:
- Indexing the table by the key itself, avoiding hashing and collisions.
class MyHashMap {
vector<int> data;
public:
MyHashMap() : data(1000001, -1) {}
void put(int key, int value) { data[key] = value; }
int get(int key) { return data[key]; }
void remove(int key) { data[key] = -1; }
};Step by step
- Allocate an int array sized max-key+1, filled with -1.
- put(key, value): array[key] = value.
- get(key): return array[key] (which is -1 when never set).
- remove(key): array[key] = -1.