Insert Delete GetRandom O(1)
Explore how to implement a Random Set data structure that allows insertion, deletion, and retrieval of random elements all in average constant time. This lesson helps you understand how to efficiently support these operations, key for optimized coding interview solutions involving custom data structures.
We'll cover the following...
Statement
Implement a Random Set data structure that can perform the following operations:
- Constructor(): This initializes the Random Set object.
- Insert(): This function takes an integer, data, as its parameter and, if it does not already exist in the set, add it to the set, returning TRUE. If the integer already exists in the set, the function returns FALSE.
- Delete(): This function takes an integer, data, as its parameter and, if it exists in the set, removes it, returning TRUE. If the integer does not exist in the set, the function returns FALSE.
- GetRandom(): This function takes no parameters. It returns an integer chosen at random from the set.
Note: Your implementation should aim to have a running time of (on average) for each operation.
Constraints:
- data
- No more than calls will be made to the Insert(), Delete() and GetRandom() functions.
- There will be at least one element in the data structure when the GetRandom() function is called.
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Insert Delete GetRandom O(1)
What is the output for the following series of commands?
Delete(20), Insert(20), Insert(20), GetRandom()
FALSE, TRUE, TRUE, 20
FALSE, TRUE, FALSE, 20
TRUE, TRUE, TRUE, 20
FALSE, FALSE, TRUE, 20
Figure it out!
We have a game for you to play. Rearrange the logical building blocks required to implement the Delete operation.
Try it yourself
Implement your solution in the following coding playground.
class RandomSet():# Initialize your data structure heredef __init__(self):# Write your code herepass# Inserts a value in the data structure# Returns True if it did not already contain the specified elementdef insert(self, val):# Write your code herepass# Removes a value from the data structure# Returns True if it contained the specified elementdef delete(self, val):# Write your code herepass# Choose an element at random from the data structure.def get_random(self):# Write your code herepass