Insert Delete GetRandom O(1)
MediumTop Interview 150 Arrays & HashingCitadelBloombergAffirmPocket GemsAxonGrammarlyProblem
Build a class RandomizedSet that stores a set of distinct integers. It needs these operations:
RandomizedSet()creates an empty set.insert(val)addsvalif it is not already present. Returntrueif it was added,falseif it was already there.remove(val)removesvalif present. Returntrueif it was removed,falseif 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
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.