1. Dynamic Array with Linear Search
Intuition
Keep elements in a resizable array. insert checks if the value is present in O(N). remove finds the index in O(N) and shifts remaining elements left in O(N). getRandom picks an index in O(1).
When to apply: When elements are few (N <= 100).
Algorithm
- Step 1: In insert(val), iterate through array; if found return false; else append and return true.
- Step 2: In remove(val), find index; if not found return false; else erase element and shift remaining elements.
- Step 3: In getRandom(), pick random index between 0 and size - 1 and return array[idx].
#include <iostream>#include <vector>#include <algorithm>#include <cstdlib> using namespace std; class RandomizedSet { vector<int> nums;public: RandomizedSet() {} bool insert(int val) { if (find(nums.begin(), nums.end(), val) != nums.end()) return false; nums.push_back(val); return true; } bool remove(int val) { auto it = find(nums.begin(), nums.end(), val); if (it == nums.end()) return false; nums.erase(it); return true; } int getRandom() { int idx = rand() % nums.size(); return nums[idx]; }}; int main() { RandomizedSet rSet; cout << boolalpha; cout << "insert(1): " << rSet.insert(1) << endl; // true cout << "remove(2): " << rSet.remove(2) << endl; // false cout << "insert(2): " << rSet.insert(2) << endl; // true cout << "getRandom(): " << rSet.getRandom() << endl; // 1 or 2 cout << "remove(1): " << rSet.remove(1) << endl; // true cout << "getRandom(): " << rSet.getRandom() << endl; // 2 return 0;}Time & Space Complexity
- Time complexity:
O(N) insert/remove, O(1) getRandom - Space complexity:
O(N)