You need to implement a RandomizedSet class that stores unique integers.
| Operation | Description | Return value |
|---|---|---|
insert(val) |
Insert val if it doesn't exist |
True if inserted; otherwise False |
remove(val) |
Remove val if it exists |
True if removed; otherwise False |
getRandom() |
Return a randomly selected element from the set | An existing element, with each element equally likely to be selected |
Pattern: Array + Hash Map
We need two data structures because neither a list nor a hash set alone can efficiently support all three operations.
| Data structure | Purpose | Average time |
|---|---|---|
List (self.nums) |
Store values so we can randomly select an index | O(1) for index access |
Dictionary (self.indices) |
Map each value to its index in the list | O(1) for lookup, insertion, and deletion |
Suppose our data structures look like this:
self.nums = [10, 20, 30, 40]
self.indices = {
10: 0,
20: 1,
30: 2,
40: 3
}
| Edge case | Operation | Expected result |
|---|---|---|
| Insert into an empty set | insert(5) |
True |
| Insert a duplicate | insert(5) when 5 exists |
False |
| Remove a nonexistent value | remove(9) when 9 doesn't exist |
False |
| Remove the only element | remove(5) from [5] |
True; set becomes empty |
| Remove the last element | remove(30) from [10, 20, 30] |
True |
| Remove a middle element | remove(20) from [10, 20, 30] |
True; swap with the last element |
| Insert after removal | Remove 5, then insert 5 |
Both operations return True |
| Random selection | getRandom() |
Returns an existing element, uniformly at random |
The simplest approach is to use a list to store the values.
insert(val): Check whether the value exists, then append it.remove(val): Search for the value and remove it.getRandom(): Choose a random element from the list.