Problem
Design a set that supports insert, remove and getRandom, each in average O(1) time. getRandom should return each current element with equal probability.
Original: LeetCode 380: Insert Delete GetRandom O(1).
Examples
Example 1
`RandomizedSet: insert(1), remove(2), insert(2), getRandom(), remove(1), insert(2), getRandom()``[null, true, false, true, 1 or 2, true, false, 2]`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.
Hints
Hint 1
insert and remove return whether the value was added or removed. Values are unique. getRandom is only called when the set is not empty.
Hint 2
O(1) random access needs a packed array. O(1) deletion needs a map from value to its index, plus a swap-with-last trick.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. A HashSet gives O(1) insert and remove, but picking a random element is linear. A list gives O(1) random access, but remove is linear.
Optimal. ArrayList plus HashMap. On remove, overwrite the target index with the last value, update that value's index, then drop the last slot.
Alternative. A tree set cannot pick a uniform random element in O(1).
Complexity
- Time
- O(1)
insert, remove and getRandom are average O(1) time. Space is O(n).
- Space
- O(n)
Code
import random
class RandomizedSet:
def __init__(self) -> None:
self.values: list[int] = []
self.index: dict[int, int] = {}
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
at = self.index[val]
last = self.values[-1]
self.values[at] = last
self.index[last] = at
self.values.pop()
del self.index[val]
return True
def get_random(self) -> int:
return random.choice(self.values)
if __name__ == "__main__":
s = RandomizedSet()
assert s.insert(1) is True
assert s.remove(2) is False
assert s.insert(2) is True
seen = {s.get_random() for _ in range(20)}
assert seen == {1, 2}
assert s.remove(1) is True
assert s.insert(2) is False
assert s.get_random() == 2
print("ok")import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
public class InsertDeleteGetRandomO1 {
private final List<Integer> values = new ArrayList<>();
private final Map<Integer, Integer> index = new HashMap<>();
private final Random random = new Random(0);
boolean insert(int val) {
if (index.containsKey(val)) return false;
index.put(val, values.size());
values.add(val);
return true;
}
boolean remove(int val) {
var at = index.get(val);
if (at == null) return false;
int last = values.get(values.size() - 1);
values.set(at, last);
index.put(last, at);
values.remove(values.size() - 1);
index.remove(val);
return true;
}
int getRandom() {
return values.get(random.nextInt(values.size()));
}
public static void main(String[] args) {
var s = new InsertDeleteGetRandomO1();
if (!s.insert(1)) throw new AssertionError();
if (s.remove(2)) throw new AssertionError();
if (!s.insert(2)) throw new AssertionError();
Set<Integer> seen = new HashSet<>();
for (int i = 0; i < 20; i++) seen.add(s.getRandom());
if (!seen.equals(Set.of(1, 2))) throw new AssertionError(seen);
if (!s.remove(1)) throw new AssertionError();
if (s.insert(2)) throw new AssertionError();
if (s.getRandom() != 2) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official sample: insert 1, remove 2 is false, insert 2, getRandom is 1 or 2, remove 1, insert 2 is false, then getRandom is 2.
- When you remove the last element, the swap-with-self is harmless as long as you delete the map entry after the swap.
Follow-ups
- Insert Delete GetRandom with duplicates needs a map from value to a set of indices.
Interview script
"I keep a compact array for getRandom and a map from value to index for lookups. To delete in O(1) I swap the target with the last element, fix that element's index, and pop the tail."
Source: LeetCode 380: Insert Delete GetRandom O(1) Source: Java SE 17 API: Random.nextInt)
Caches and time-indexed lookup
Sources (2)
- LeetCode 380: Insert Delete GetRandom O(1)leetcode.com
- Java SE 17 API: Random.nextIntdocs.oracle.com