Insert Delete GetRandom O(1)
Hashing
Problem Statement
Implement the
RandomizedSet class:RandomizedSet()Initializes theRandomizedSetobject.bool insert(int val)Inserts an itemvalinto the set if not present. Returnstrueif the item was not present,falseotherwise.bool remove(int val)Removes an itemvalfrom the set if present. Returnstrueif the item was present,falseotherwise.int getRandom()Returns a random element from the current set of elements. 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.
Solution (Hash Map + Array)
To achieve O(1) time complexity for all operations, we can use a combination of a hash map and an array. The hash map will store the value and its index in the array, and the array will store the values themselves.
Algorithm Steps
- Insert: Add the value to the end of the array and store its index in the hash map.
- Remove: To remove an element in O(1), we swap it with the last element in the array, update the hash map for the swapped element, and then pop from the array.
- GetRandom: Simply pick a random index from the array.
Map (Value → Index)
List
Perform an operation.
Insert Delete GetRandom O(1) Solution