1. Direct Access Array
Intuition
Initialize an array of size 1000001 with all entries set to -1. Put sets arr[key] = value, get returns arr[key], and remove sets arr[key] = -1.
When to apply: When memory is unconstrained and key domain is strictly bounded small integers.
Algorithm
- Step 1: In constructor, allocate array of size 1000001 filled with -1.
- Step 2: put(key, val): arr[key] = val.
- Step 3: get(key): return arr[key].
- Step 4: remove(key): arr[key] = -1.
#include <iostream>#include <vector> using namespace std; 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; }}; int main() { MyHashMap myMap; myMap.put(1, 1); myMap.put(2, 2); cout << "get(1): " << myMap.get(1) << endl; // 1 cout << "get(3): " << myMap.get(3) << endl; // -1 myMap.put(2, 1); cout << "get(2): " << myMap.get(2) << endl; // 1 myMap.remove(2); cout << "get(2): " << myMap.get(2) << endl; // -1 return 0;}Time & Space Complexity
- Time complexity:
O(1) for all operations - Space complexity:
O(M) where M = 10^6