Skip to content
Onsite

Insert Delete GetRandom O(1)

MediumP2Coding

Design a set of integers that supports insert, delete and picking a random element, all in O(1) average time.

Implement the RandomizedSet class:

  • RandomizedSet() creates an empty set.
  • insert(val) adds val and returns true, or returns false if it was already present.
  • remove(val) removes val and returns true, or returns false if it was not present.
  • getRandom() returns a uniformly random element of the current set. It is only called when the set is not empty.
  • contains(val) and size() report membership and the number of elements (added so the tests can check state).

Random output cannot be compared exactly, so the tests call getRandom() only when the set holds exactly one element.

Example 1

Input
["RandomizedSet","insert","remove","insert","size","remove","getRandom"] [[],[1],[2],[2],[],[1],[]]
Output
[null,true,false,true,2,true,2]
Why
With one element left, getRandom must return it.

Constraints

  • -2^31 <= val <= 2^31 - 1
  • At most 2 * 10^5 calls.
  • getRandom is only called on a non-empty set.

Hints

Run checks the 2 visible tests, Submit all 7.