1. Direct Boolean Array
Intuition
Create a boolean array of size 1000001. add sets arr[key] = true, remove sets arr[key] = false, and contains returns arr[key].
When to apply: When keys are bounded non-negative integers up to 106 and memory is plentiful.
Algorithm
- Step 1: Allocate boolean array of size 1000001 initialized to false.
- Step 2: add(key): arr[key] = true.
- Step 3: remove(key): arr[key] = false.
- Step 4: contains(key): return arr[key].
#include <iostream>#include <vector> using namespace std; class MyHashSet { vector<bool> table;public: MyHashSet() : table(1000001, false) {} void add(int key) { table[key] = true; } void remove(int key) { table[key] = false; } bool contains(int key) { return table[key]; }}; int main() { MyHashSet mySet; mySet.add(1); mySet.add(2); cout << boolalpha; cout << "contains(1): " << mySet.contains(1) << endl; // true cout << "contains(3): " << mySet.contains(3) << endl; // false mySet.add(2); cout << "contains(2): " << mySet.contains(2) << endl; // true mySet.remove(2); cout << "contains(2): " << mySet.contains(2) << endl; // false return 0;}Time & Space Complexity
- Time complexity:
O(1) strictly for all operations - Space complexity:
O(M) where M = 10^6