Video in progress

Strong Middle 🧠 Problem solving

How do you write a set where insert, remove and getRandom are all O(1) on average?

An ArrayList stores the elements and gives a random index in O(1), while a HashMap takes you from a value to its index. On removal I put the last element of the list in the removed element's place and drop the last slot, so nothing gets shifted.

📖 Answer

A HashSet can't do getRandom by itself: to reach a random element you have to walk with an iterator, which is O(n). In an ArrayList, remove(Object) is O(n). We combine the two.

final class RandomizedSet {
    private final List<Integer> items = new ArrayList<>();
    private final Map<Integer, Integer> index = new HashMap<>();   // value -> its position in items

    boolean insert(int x) {
        if (index.containsKey(x)) return false;
        index.put(x, items.size());
        items.add(x);
        return true;
    }

    boolean remove(int x) {
        Integer i = index.remove(x);
        if (i == null) return false;
        int last = items.remove(items.size() - 1);   // by index — we take the last one
        if (i < items.size()) {                       // the removed one wasn't the last
            items.set(i, last);
            index.put(last, i);
        }
        return true;
    }

    int getRandom() {
        return items.get(ThreadLocalRandom.current().nextInt(items.size()));
    }
}

The subtle point is the if inside remove. Without it, when the element being removed is itself the last one, items.set(i, last) throws an IndexOutOfBoundsException, because i is already past the end of the list (and if it didn't, index.put(last, i) would put the just-removed key back into the map). It's easy to check: insert(5), remove(5).

Another trap: in a List<Integer>, remove(int) removes by index and remove(Object) removes by value. Above, the index form is used on purpose.

In the variant that allows duplicates, you use Map<Integer, Set<Integer>>, a set of indexes for each value. The logic is the same; you just take the index to be replaced from the set.

In practice: a random user for an A/B test, a random opponent in a game, picking a random one among healthy servers.