Design Data Structures · Pattern 5 of 10

Hash map + array: O(1) insert, delete and random

An array can return a random element in O(1) but cannot delete from the middle. A hash map from value to index fixes that: move the last element into the hole, update its index, then pop the end.

2 variations · 4 problems

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Insert, delete and get a random element, all in O(1)
  • Remember the last time something was seen
  • A few fixed categories with a counter each

The template

Hash Map + Array
class RandomizedSet {
    List<Integer> vals = new ArrayList<>();
    Map<Integer, Integer> idx = new HashMap<>();     // value -> its index in vals
    Random rnd = new Random();
    boolean insert(int val) {
        if (idx.containsKey(val)) return false;
        idx.put(val, vals.size());
        vals.add(val);
        return true;
    }
    boolean remove(int val) {
        Integer i = idx.remove(val);
        if (i == null) return false;
        int last = vals.remove(vals.size() - 1);     // removing the end is O(1)
        if (i < vals.size()) {                       // fill the hole with the last value
            vals.set(i, last);
            idx.put(last, i);
        }
        return true;
    }
    int getRandom() { return vals.get(rnd.nextInt(vals.size())); }
}

The variations

  1. 1Swap with the last, then pop

    Order in the array does not matter, so move the last element into the removed slot. Every operation touches at most two entries. With duplicates, each value maps to a set of its indexes, and the same swap keeps them correct.

  2. 2A map or array of small facts

    Sometimes one number per key is the whole state. A rate limiter stores the next time each message may print. A parking lot keeps three counters in an array indexed by car type.

Mistakes to avoid

  • Removing the value from the middle of the array: that shifts everything, O(n).
  • Updating the moved value's index in the wrong order when the removed value is itself the last one: it gets re-added to the map.
  • With duplicates allowed, mapping each value to one index: map it to a set of indexes instead.
Next: Hash map + heap: expiring keys in time order →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.