DIY: Insert Delete GetRandom O(1) - Duplicates Allowed

Solve the interview question "Insert Delete GetRandom O(1) - Duplicates Allowed" in this lesson.

Problem statement

Implement a set data structure that allows duplicates and can perform the following operations:

  • Insert(data): This function should insert data into the set (if the set does not contain it already). It should return false if the data already exists in the set. Otherwise, it should return true.
  • Remove(data): If the data is present, this function should remove data from the set and return true. If the data does not exist in the set, the function should return false.
  • GetRandom(): This function should return a random element from the set in constant time.

Note: Your implementation should aim for constant running time (on average) for each operation.

Constraints

  • 231-2^{31} <= value <= 23112^{31} - 1
  • At most 21052 * 10^{5} calls in total will be made to Insert(), Remove(), and GetRandom().
  • There will be at least one element in the data structure to call getRandom().

Input

You will insert, delete and get the random values using the Insert(), Remove() ,and GetRandom() methods of the class respectively. Let’s see how to insert, delete and get the random values below:

insert(1)
insert(1)
insert(2)
getRandom()
remove(1)
remove(1)
insert(1)
insert(2)
insert(3)
getRandom()
remove(2)
remove(2)

Output

The following is the output of the above input:

true
false
true
1 or 2
true	
true
true
false
true
1 or 2 or 3	
true
true

Coding exercise

Implement the RandomizedCollection class and initialize its empty object. Create three methods Insert(), Remove(), and GetRandom() of RandomizedCollection class. The Insert() and Remove() methods return true or false, and the GetRandom() method return integer number.

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.