DIY: Insert Delete GetRandom O(1) - Duplicates Allowed
Solve the interview question "Insert Delete GetRandom O(1) - Duplicates Allowed" in this lesson.
We'll cover the following
Problem statement
Implement a set data structure that allows duplicates and can perform the following operations:
The
obj
parameter being passed as an argument in theinsert()
,remove()
,andget_random()
methods refers to the struct object.
insert(obj, data)
: This function should insertdata
into the set (if the set does not contain it already). It should returnfalse
if thedata
already exists in the set. Otherwise, it should returntrue
.remove(obj, data)
: If thedata
is present, this function should removedata
from the set and returntrue
. If thedata
does not exist in the set, the function should returnfalse
.get_random(obj)
: 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
- <=
value
<= - At most calls in total will be made to
insert()
,remove()
, andget_random()
. - There will be at least one element in the data structure to call
get_random()
.
Input
You will insert, delete and get the random values using the insert()
, remove()
,and get_random()
methods of the module respectively. Let’s see how to insert, delete and get the random values below:
insert(1)
insert(1)
insert(2)
get_random()
remove(1)
remove(1)
insert(1)
insert(2)
insert(3)
get_random()
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
module and initialize its empty object. Create three methods insert()
, remove()
, and get_random()
of RandomizedCollection
module. The insert()
and remove()
methods return true or false, and the get_random()
method return integer number.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.