TRT
Sign in
mediumFoundationsLeetCode#swap with last#array plus hash map

Insert delete getrandom O(1)

Design a set that inserts, removes and returns a uniformly random element, each in O(1) on average.

The Runtime Theory Team1 min read
Taught inInserting and deleting in the middleAn array has no gaps, so inserting or deleting anywhere but the end shifts everything after that point. Knowing that cost, and the tricks that avoid it, decides how you use arrays.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

ininsert(1), remove(2), insert(2), getRandom()

out1 or 2, each with probability 1/2

ininsert(1), remove(1), insert(1)

outtrue, true, true

inset holds 4, 8, 9; getRandom()

out4, 8 or 9, uniformly

Implement a set with insert(val), remove(val) and getRandom(). insert and remove return whether they changed the set. getRandom returns each element with equal probability. All three should run in O(1) time on average.

Before you code

A hash set gives O(1) insert and remove, but no way to pick a random element without walking it. An array gives an O(1) random pick, by choosing a random index, but O(n) removal. You need both, kept in sync.

Hints

  1. Store the values in an array, and a hash map from each value to its index in the array.
  2. To remove a value, look up its index, move the last element of the array into that index, update the moved element's entry in the map, then pop the last slot. No shifting.
  3. Handle the case where the value being removed is itself the last element.

Production & complexity notes

When solving Insert delete getrandom O(1) on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Inserting and deleting in the middle to reinforce the underlying pattern.

What it practices

The swap-with-last delete, from Inserting and deleting in the middle, combined with a hash map.

Not started

Sign in to save your learning progress.

Sign in to save