# [380\. Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) :::spoiler Hint ```cpp= class RandomizedSet { private: // Map to store value and its index in the vector // Vector to store the values public: RandomizedSet() {} bool insert(int val) { // If the value is already in the set, return false // Add the value to the end of the vector // Map the value to its index in the vector // Successfully inserted } bool remove(int val) { // If the value is not in the set, return false // Get the last element in the vector // Move the last element to the position of the element to be removed // Remove the last element from the vector // Erase the element from the map // Successfully removed } int getRandom() { // Return a random element from the vector } }; /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet* obj = new RandomizedSet(); * bool param_1 = obj->insert(val); * bool param_2 = obj->remove(val); * int param_3 = obj->getRandom(); */ ``` ::: :::spoiler Solution ```cpp= class RandomizedSet { private: unordered_map<int, int> m; vector<int> nums; public: RandomizedSet() {} bool insert(int val) { if(m.count(val)) return false; nums.push_back(val); m[val] = nums.size() - 1; return true; } bool remove(int val) { if (!m.count(val)) return false; int lastElement = nums.back(); nums[m[val]] = lastElement; m[lastElement] = m[val]; nums.pop_back(); m.erase(val); return true; } int getRandom() { return nums[rand() % nums.size()]; } }; /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet* obj = new RandomizedSet(); * bool param_1 = obj->insert(val); * bool param_2 = obj->remove(val); * int param_3 = obj->getRandom(); */ ``` - Time Complexity: $O(1)$ - Space Complexity: $O(N)$ :::