Insert Delete GetRandom O(1)
The key idea
Pair a dynamic array (for O(1) uniform random pick by index) with a hash map of value -> its index in the array (for O(1) membership and delete). To delete without shifting, swap the doomed element with the last array element, fix the moved element's index in the map, then pop the tail.
Problem
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 is 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.
Constraints
-2^31 <= val <= 2^31 - 1- At most
2 * 10^5calls will be made toinsert,remove, andgetRandom. - There will be at least one element in the data structure when
getRandomis called.
Examples
Input: ["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
Output: [null, true, false, true, 2, true, false, 2]
Input: ["RandomizedSet", "insert", "insert", "remove", "getRandom"]
[[], [10], [20], [10], []]
Output: [null, true, true, true, 20]
Complexity
Time: O(1) Space: O(n)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Design problems
- Binary Search Tree IteratorMEDIUM
- Design Circular QueueMEDIUM
- Design HashMapEASY
- Design HashSetEASY
- Design TwitterMEDIUM
- Detect SquaresMEDIUM
- Encode and Decode StringsMEDIUM
- Implement Queue using StacksEASY
- Implement Stack using QueuesEASY
- LFU CacheHARD
- LRU CacheMEDIUM
- Maximum Frequency StackHARD