Skip to content
Decoder

Insert Delete GetRandom O(1)

Medium

Problem

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.

Example 1

s = RandomizedSet()

Example 2

Input
s.insert(1)
Output
true

Example 3

Input
s.remove(2)
Output
false

Example 4

Input
s.insert(2)
Output
true

Example 5

Input
s.get_random()
Output
1 or 2

Example 6

Input
s.remove(1)
Output
true

Example 7

Input
s.get_random()
Output
2
Why
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.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.