Insert Delete GetRandom O(1)
Implement the `RandomizedSet` class: - `RandomizedSet()` Initializes the `RandomizedSet` object. - `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise. - `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise. - `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned. You must implement the functions of the class such that each function works in **average** `O(1)` time complexity.
Examples
Constraints
-2^31 <= val <= 2^31 - 1At most 2 * 10^5 calls will be made to insert, remove, and getRandom.There will be at least one element in the data structure when getRandom is called.
Optimal Solution
Approach
To achieve O(1) average time complexity for `insert`, `remove`, and `getRandom`, we need to use a combination of a hash map and a dynamic array (or list). 1. **Dynamic Array**: We store the elements in an array. This allows us to access a random element in O(1) time by picking a random index between `0` and `length - 1`. 2. **Hash Map**: We use a hash map to store the mapping from a value to its index in the array. This allows us to check if an element exists and find its location in O(1) time. **Insert Operation**: - Check if the value exists in the hash map. If it does, return `false`. - If not, append the value to the end of the array. - Add the value and its index (which is `array.length - 1`) to the hash map. - Return `true`. **Remove Operation**: - Check if the value exists in the hash map. If not, return `false`. - To remove an element in O(1) time from an array without shifting elements, we can swap the element to be removed with the **last element** in the array. - Get the index of the element to remove from the hash map. - Get the value of the last element in the array. - Swap the elements: set the value at the removed element's index to the last element's value. - Update the hash map: update the index of the last element's value to the removed element's index. - Remove the last element from the array (which is now O(1)). - Remove the deleted element's entry from the hash map. - Return `true`. **GetRandom Operation**: - Generate a random integer between `0` and the current size of the array minus 1. - Return the element at that random index in the array.