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(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(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_data()
: 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 get_random_data()
function will have no input.
insert(20)
get_random_data()
remove(20)
Output
The outputs of the insert()
and remove()
functions will be Booleans. While the get_random_data()
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.