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:

Example 1
Input: insert(1), insert(1), insert(2), getRandom(), remove(1), getRandom()
Output: true, false, true, 1 with probability 2/3 or 2 with probability 1/3, true, 1 or 2 with probability 1/2 each
Solution

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) returns true, because 1 is new. The second returns false, because a 1 is already there, yet the bag now holds two marbles marked 1. After insert(2) the bag holds 1, 1 and 2, so a blind pick gives 1 two times out of three. Then remove(1) takes out one of the 1s, and the next pick gives 1 or 2 equally often.

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.

Before remove(1) the list of copies is 1, 1, 2 in slots 0 to 2, and the map holds 1 to slots {0, 1} and 2 to slot {2}. Slot 0 is the hole and the last copy, 2, moves into it. After remove(1) the list is 2, 1, slot 2 is dropped, and the map holds 1 to {1} and 2 to {0}.

The picture shows that remove(1) from Example 1. In the half labelled "before remove(1)", the map row for 1 lists slots {0, 1}, and slot 0 is taken as the hole. The last copy, the 2 in slot 2, follows the teal arrow into slot 0. In the half labelled "after remove(1)", the list reads 2, 1, slot 2 is dropped, and the map row for 2 has changed from {2} to {0}.

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 remove finds a copy, how it fills the hole, what happens when the hole is itself the last slot, and how getRandom picks.

Finding a copy of a value

How does remove(1) know where a 1 sits? Reading the list slot by slot would make it slower as the collection grows. The map, a HashMap, answers in one lookup instead. Each value leads to a HashSet of its slots, and a set is needed because one value can sit in several slots, as 1 does in {0, 1}.

A HashSet adds and removes a slot in O(1) time on average, as its documentation states, and iterator().next() hands out any one of its slots. The set also gives insert its return value: if the value's set holds exactly one slot after the new one is added, the value was not stored before.

Filling the hole

Which copy goes into the hole? The one in the last slot, because removing the last element of an ArrayList shifts nothing. The moved value then needs two changes in its own set: it gains the hole and loses its old slot, the last one.

When the removed value has no slots left, its entry leaves the map. A later remove of that value then finds no entry and returns false straight away.

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 getRandom give every copy the same chance? It asks a java.util.Random for nextInt(size), a whole number from 0 up to the list size minus one, each equally likely, and returns the value in that slot. With 1, 1 and 2 stored, two of the three slots hold a 1.

Java Solution

The class has these parts:

  • values: the list of copies, an ArrayList with one copy per slot. The method getRandom reads it.
  • positions: the map from each value to the HashSet of its slots. The method insert adds a slot to it, and remove takes one out.
  • random: the Random that getRandom uses, passed in through the constructor so that main can give it a fixed seed.
  • insert, remove and getRandom: the three methods of the problem.
  • state and countPicks: two helpers for printing. The first shows the list and the map with keys and slots sorted, and the second calls getRandom a given number of times and counts how often each value comes out.

The main method runs Example 1, with 30,000 counted picks in place of each single getRandom(), and uses the seed 42 so every run prints the same counts. Then it removes a value that was never stored, removes 1 until none is left, empties the collection and inserts into it again.

Java
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:

Output
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), the map reads {1=[0, 1], 2=[2]}, the left half of the picture. With those three copies stored, the 30,000 picks gave 1 a total of 19,831 times and 2 a total of 10,169 times, close to two thirds and one third. The remove(1) line after it matches the right half: values=[2, 1], with 1 in slot 1 and 2 in slot 0. The next 30,000 picks split 15,124 to 14,876, close to half each.

Below that, remove(5) returns false and leaves both structures as they were. The following remove(1) takes slot 1, which is also the last slot, so the copy moves onto itself and the slot is dropped. The map then has no entry for 1, and the next remove(1) returns false. In the last two lines, remove(2) leaves values=[], and insert(2) returns true again, since 2 is no longer stored.

The order of the two set updates in remove is easy to get wrong. Swap the two lines, taking out the old last slot before adding the hole, and a collection holding a single 1 prints:

Output
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) empties the list but leaves positions={1=[0]}, because the hole, slot 0, was added back after the removal had nothing to take out. The second remove(1) trusts that stale slot, computes lastIndex as -1 on the empty list, and values.get(-1) throws.

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, remove and getRandom, because each touches the list only at its end or at a slot it already knows, and makes a few HashMap and HashSet calls, which take constant time on average.
  • Space: O(n) for n stored copies, because each copy fills one slot of values and its slot number sits in exactly one set of positions.

The version that stores each number at most once is Insert Delete GetRandom O(1).