Skip to content

Insert Delete GetRandom O(1)

MediumArrays & Hashing
Decode it first. Clues, constraints, pattern and plan before any code.

Build a class RandomizedSet that stores distinct integers and supports three operations, each in average O(1) time:

  • insert(val): add val if it is not already present. Return true if it was added, false if it was already there.
  • remove(val): delete val if present. Return true if it was removed, false if it was not there.
  • get_random() (getRandom in TypeScript): return a random current element, where every element is equally likely.
s = RandomizedSet()
s.insert(1)      →  true
s.remove(2)      →  false
s.insert(2)      →  true
s.get_random()   →  1 or 2
s.remove(1)      →  true
s.get_random()   →  2   (the only element left)

Constraints

  • -2^31 <= val <= 2^31 - 1
  • At most 2 * 10^5 calls in total.
  • get_random is only called when the set is not empty.