1. Dynamic Array with Linear Removal
Intuition
Keep all elements in a vector. insert checks if present (to return boolean flag) and appends. remove searches for the first occurrence of val, erases it in O(N), and shifts remaining elements. getRandom picks a random index.
When to apply: When total operations are few.
Algorithm
- Step 1: In insert(val), check if val in array; append val; return !present.
- Step 2: In remove(val), find index of val; if not found return false; else erase at index and return true.
- Step 3: In getRandom(), return array[rand() % size].
#include <iostream>#include <vector>#include <algorithm>#include <cstdlib> using namespace std; class RandomizedCollection { vector<int> nums;public: RandomizedCollection() {} bool insert(int val) { bool present = (find(nums.begin(), nums.end(), val) != nums.end()); nums.push_back(val); return !present; } 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() { return nums[rand() % nums.size()]; }}; int main() { RandomizedCollection rc; cout << boolalpha; cout << "insert(1): " << rc.insert(1) << endl; // true cout << "insert(1): " << rc.insert(1) << endl; // false cout << "insert(2): " << rc.insert(2) << endl; // true cout << "getRandom(): " << rc.getRandom() << endl; cout << "remove(1): " << rc.remove(1) << endl; // true cout << "getRandom(): " << rc.getRandom() << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N) insert/remove, O(1) getRandom - Space complexity:
O(N)