AAlgoLoopSpaced repetition for LeetCode
MEDIUMDesignLeetCode ↗

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

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

410310
Step-by-step visualization
Start free →

More Design problems