Insert Delete GetRandom O(1)
Implement a RandomizedSet class that stores a set of integers and supports three operations, each in O(1) average time:
insert(val)addsvalif it isn't already in the set. Returntrueif it was added andfalseif it was already there.remove(val)removesvalif it's in the set. Returntrueif it was removed andfalseif it wasn't there.get_random()returns a random value from the set. Every value currently in the set must be equally likely. It's only called when the set isn't empty.
The tests run a sequence of operations on one set. In the output, insert and remove show 1 for true and 0 for false. Each get_random in the sequence is called 300 times, and its output is how many different values came back, or -1 if any of them wasn't in the set. A fair get_random returns every value at least once in 300 calls.
Example 1
Input: ["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"] [[], [1], [2], [2], [], [1], [2], []] Output: [1, 0, 1, 2, 1, 0, 1]
remove(2) fails because 2 isn't in the set yet. After inserting 2, the set is {1, 2}, so get_random returns both values. After removing 1, inserting 2 again fails, and get_random can only return 2.
Example 2
Input: ["RandomizedSet", "insert", "insert", "insert", "insert", "remove", "remove", "getRandom"] [[], [10], [20], [30], [40], [20], [10], []] Output: [1, 1, 1, 1, 1, 1, 2]
Only 30 and 40 remain, and get_random must keep returning both of them.
Constraints
-2^31 <= val <= 2^31 - 1- At most
2 * 10^5calls are made in total. get_randomis only called when the set has at least one value.
Approach
A hash set alone handles insert and remove in O(1), but it can't return a uniformly random element without walking through it. An array alone handles random picks with one random index, but finding and deleting a value takes O(n).
Use both. Store the values in an array, and keep a hash map from each value to its index in the array. insert appends to the array and records the index. get_random picks a random index. The tricky part is remove: deleting from the middle of an array shifts everything after it. Since the order doesn't matter, move the last value into the removed value's slot instead, update the moved value's index in the map, then pop the end of the array. Every step is O(1).
Steps
- Keep an array
valuesand a mapindexfrom value to position. - In
insert, returnfalseif the value is in the map. Otherwise record its index as the array's length, append it and returntrue. - In
remove, returnfalseif the value isn't in the map. Otherwise copy the last value into the removed value's position, update that last value's index, pop the array, delete the removed value from the map and returntrue. - In
get_random, return the value at a random index.
import random
class RandomizedSet:
def __init__(self):
self.values = [] # the set's values, in no particular order
self.index = {} # value -> its position in self.values
def insert(self, val: int) -> bool:
if val in self.index:
return False
self.index[val] = len(self.values)
self.values.append(val)
return True
def remove(self, val: int) -> bool:
if val not in self.index:
return False
i = self.index[val]
last = self.values[-1]
self.values[i] = last # move the last value into the gap
self.index[last] = i
self.values.pop() # removing from the end is O(1)
del self.index[val]
return True
def get_random(self) -> int:
return random.choice(self.values)Complexity
- Time:
O(1)average for every operation. Each is a fixed number of hash map and array-end operations. - Space:
O(n)for the array and the map.
Common mistakes
- Deleting from the middle of the array with a shifting removal, which is
O(n). - Forgetting to update the moved value's index in the map, so a later
removeof that value touches the wrong slot. - Deleting the removed value from the map before reading its index, or updating the map in an order that breaks when the removed value is itself the last one.
HashMap supports insert, search, delete and retrieve in O(1). It stores data as key value pairs.