DIY: Insert, Delete, and GetRandom in O(1)
Solve the interview question "Insert, Delete, and GetRandom in O(1)" in this lesson.
We'll cover the following
Problem statement
Implement a set data structure that can perform the following operations:
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
.getRandomData(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.
Input
The inputs to the insert()
and remove()
functions will be integers. The getRandomData()
function will have no input.
Note: All three functions will have the struct object,
obj
, as its parameter.
insert(%RandomSet{}, 20)
getRandomData(%RandomSet{})
remove(%RandomSet{}, 20)
Output
The outputs of the insert()
and remove()
functions will be Booleans. While the getRandomData()
function will return an integer. The following is an example output that corresponds to the input given above:
true
20
true
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.