Skip to main content

Insert Delete GetRandom O(1)

MediumPremium

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

  • insert(val) adds val if it isn't already in the set. Return true if it was added and false if it was already there.
  • remove(val) removes val if it's in the set. Return true if it was removed and false if it wasn't there.
  • get_random() returns a random value from the set. Every value currently in the set must be equally likely. It's only called when the set isn't empty.

The tests run a sequence of operations on one set. In the output, insert and remove show 1 for true and 0 for false. Each get_random in the sequence is called 300 times, and its output is how many different values came back, or -1 if any of them wasn't in the set. A fair get_random returns every value at least once in 300 calls.

Example 1

Input: ["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"] [[], [1], [2], [2], [], [1], [2], []] Output: [1, 0, 1, 2, 1, 0, 1]

remove(2) fails because 2 isn't in the set yet. After inserting 2, the set is {1, 2}, so get_random returns both values. After removing 1, inserting 2 again fails, and get_random can only return 2.

Example 2

Input: ["RandomizedSet", "insert", "insert", "insert", "insert", "remove", "remove", "getRandom"] [[], [10], [20], [30], [40], [20], [10], []] Output: [1, 1, 1, 1, 1, 1, 2]

Only 30 and 40 remain, and get_random must keep returning both of them.

Constraints

  • -2^31 <= val <= 2^31 - 1
  • At most 2 * 10^5 calls are made in total.
  • get_random is only called when the set has at least one value.