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
.GetRandomData()
: 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.
insert(20)
getRandomData()
remove(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 70+ hands-on prep courses.