CodingNodes / Arrays & Hashing / Insert Delete GetRandom O(1) System design Space play · ←→ step · R restart

Problem

Build a class RandomizedSet that stores a set of distinct integers. It needs these operations:

  • RandomizedSet() creates an empty set.
  • insert(val) adds val if it is not already present. Return true if it was added, false if it was already there.
  • remove(val) removes val if present. Return true if it was removed, false if it was not there.
  • getRandom() returns one of the current values, each equally likely.

Every operation must run in average O(1) time. The input is a list of calls and their arguments; the output lists what each call returns (null for the constructor). In the examples below, getRandom is only called when the set holds a single value, so its result is predictable.

Constraints

  • −2³¹ ≤ val ≤ 2³¹ − 1
  • getRandom is only called when the set is not empty
  • At most 2 · 10⁵ calls in total

Examples: pick one to animate

Solutions

TimeO(1) SpaceO(n)

Time: A hash map lookup, a list append, a swap-with-last and a list pop-from-end are each constant time on average.

Space: The list and the map each hold up to n values.

Keep the values in a list (for fast random picks) and a map from value to its list index (for fast lookups). To remove a value, copy the last list item into its slot, fix that item's index in the map, then pop the end of the list. That avoids shifting items.