Randomized Collection
Store numbers, repeats allowed, so that adding, removing and a fair random pick each take constant time.
Write a class that stores integers and may hold the same integer more than once. It needs three methods, and each must take O(1) time on average, however many numbers are stored:
- The method
adds one copy ofinsert(val) and returns true ifval was not stored before, false if it already was.val - The method
removes one copy ofremove(val) and returns true, or returns false if there is no copy to remove.val - The method
returns one of the stored numbers, where every copy has the same chance, so a number stored twice comes back twice as often.getRandom()
Example 1
Output: true, false, true, 1 with probability 2/3 or 2 with probability 1/3, true, 1 or 2 with probability 1/2 each
The Idea
Picture a bag of marbles with a number painted on each. You can drop a marble in, take out a marble with a given number, or reach in without looking and read the number on whichever marble you touch. Two marbles may carry the same number.
Follow Example 1 with the bag. The first insert(1)insert(2)remove(1)
Which storage makes all three actions fast? A list makes the blind pick easy. Each copy gets its own position in the list, called a slot here, numbered from 0. Picking a random slot number and returning what sits there gives each copy the same chance. Adding is easy too, since a new copy goes into the next slot at the end.
Removing is the hard part. To remove a 1, we first have to find one, and reading the whole list takes as many steps as there are copies. Then, if the 1 sits at the front, every copy after it has to shift one slot to the left to close the gap.
The order of the list, though, means nothing to the random pick. It only needs every copy to have exactly one slot. So the gap, or hole, can be filled with the copy from the last slot, and the last slot dropped, which moves nothing else. To find a copy without reading the list, a map can keep, for each number, the set of slots that hold it.
The picture shows that remove(1)
So a removal never closes a gap by shifting. It moves one copy, the last one, and fixes that copy's row in the map.
Solution Approach
With a list of copies and a map of slots chosen, four questions remain: how removegetRandom
Finding a copy of a value
How does remove(1)HashMapHashSet
A HashSetiterator().next()insert
Filling the hole
Which copy goes into the hole? The one in the last slot, because removing the last element of an ArrayList
When the removed value has no slots left, its entry leaves the map. A later remove
When the hole is the last slot
What if the copy being removed already sits in the last slot? Then the hole and the last slot are the same slot, and the value that moves is the value being removed. Adding the hole to its set and then taking the last slot out cancels to nothing, so the slot ends up outside the set. That is right, because the slot is dropped from the list a moment later. The order of those two set updates matters here, because doing them the other way round breaks this case.
Picking at random
How does getRandomjava.util.RandomnextInt(size)
Java Solution
The class has these parts:
: the list of copies, anvalues with one copy per slot. The methodArrayList reads it.getRandom : the map from each value to thepositions of its slots. The methodHashSet adds a slot to it, andinsert takes one out.remove : therandom thatRandom uses, passed in through the constructor so thatgetRandom can give it a fixed seed.main ,insert andremove : the three methods of the problem.getRandom andstate : two helpers for printing. The first shows the list and the map with keys and slots sorted, and the second callscountPicks a given number of times and counts how often each value comes out.getRandom
The maingetRandom()
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;
import java.util.TreeMap;
import java.util.TreeSet;
public class RandomizedCollection {
private final List<Integer> values = new ArrayList<>(); // every copy, one per slot
private final Map<Integer, Set<Integer>> positions = new HashMap<>(); // value -> its slots
private final Random random;
public RandomizedCollection(Random random) {
this.random = random;
}
// Adds one copy of val. Returns true if val was not present before.
public boolean insert(int val) {
Set<Integer> slots = positions.computeIfAbsent(val, k -> new HashSet<>());
slots.add(values.size()); // the new copy goes into the next free slot
values.add(val);
return slots.size() == 1;
}
// Removes one copy of val. Returns false if val was not present.
public boolean remove(int val) {
Set<Integer> slots = positions.get(val);
if (slots == null) {
return false;
}
int hole = slots.iterator().next(); // any copy of val will do
slots.remove(hole);
int lastIndex = values.size() - 1;
int lastVal = values.get(lastIndex);
values.set(hole, lastVal); // the last copy moves into the hole
positions.get(lastVal).add(hole); // add the new slot first,
positions.get(lastVal).remove(lastIndex); // then forget the old one
values.remove(lastIndex); // removing the last slot shifts nothing
if (slots.isEmpty()) {
positions.remove(val); // no copies of val are left
}
return true;
}
public int getRandom() {
return values.get(random.nextInt(values.size())); // every slot equally likely
}
// The list and the map, with the map's keys and slots sorted for printing.
String state() {
Map<Integer, Set<Integer>> sorted = new TreeMap<>();
positions.forEach((v, s) -> sorted.put(v, new TreeSet<>(s)));
return "values=" + values + " positions=" + sorted;
}
// How often each value comes out of getRandom in the given number of picks.
Map<Integer, Integer> countPicks(int picks) {
Map<Integer, Integer> counts = new TreeMap<>();
for (int i = 0; i < picks; i++) {
counts.merge(getRandom(), 1, Integer::sum);
}
return counts;
}
public static void main(String[] args) {
RandomizedCollection c = new RandomizedCollection(new Random(42));
System.out.println("insert(1) -> " + c.insert(1) + " " + c.state());
System.out.println("insert(1) -> " + c.insert(1) + " " + c.state());
System.out.println("insert(2) -> " + c.insert(2) + " " + c.state());
System.out.println("30000 picks: " + c.countPicks(30000));
System.out.println("remove(1) -> " + c.remove(1) + " " + c.state());
System.out.println("30000 picks: " + c.countPicks(30000));
System.out.println("remove(5) -> " + c.remove(5) + " " + c.state());
System.out.println("remove(1) -> " + c.remove(1) + " " + c.state());
System.out.println("remove(1) -> " + c.remove(1) + " " + c.state());
System.out.println("remove(2) -> " + c.remove(2) + " " + c.state());
System.out.println("insert(2) -> " + c.insert(2) + " " + c.state());
}
}
Running it prints:
insert(1) -> true values=[1] positions={1=[0]}
insert(1) -> false values=[1, 1] positions={1=[0, 1]}
insert(2) -> true values=[1, 1, 2] positions={1=[0, 1], 2=[2]}
30000 picks: {1=19831, 2=10169}
remove(1) -> true values=[2, 1] positions={1=[1], 2=[0]}
30000 picks: {1=15124, 2=14876}
remove(5) -> false values=[2, 1] positions={1=[1], 2=[0]}
remove(1) -> true values=[2] positions={2=[0]}
remove(1) -> false values=[2] positions={2=[0]}
remove(2) -> true values=[] positions={}
insert(2) -> true values=[2] positions={2=[0]}
In the third line, after insert(2){1=[0, 1], 2=[2]}remove(1)values=[2, 1]
Below that, remove(5)remove(1)remove(1)remove(2)values=[]insert(2)
The order of the two set updates in remove
insert(1) -> true values=[1] positions={1=[0]}
remove(1) -> true values=[] positions={1=[0]}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index -1 out of bounds for length 0
The first remove(1)positions={1=[0]}remove(1)lastIndexvalues.get(-1)
Complexity
No method ever walks the list or a set, so the cost of a call does not grow with the number of stored copies.
- Time: O(1) on average for
,insert andremove , because each touches the list only at its end or at a slot it already knows, and makes a fewgetRandom andHashMap calls, which take constant time on average.HashSet - Space: O(n) for n stored copies, because each copy fills one slot of
and its slot number sits in exactly one set ofvalues .positions
The version that stores each number at most once is