...

/

Insert Delete GetRandom O(1)

Insert Delete GetRandom O(1)

Try to solve the Insert Delete GetRandom O(1) problem.

Statement

Implement a Random Set data structure that can perform the following operations:

  • Init(): 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 O(1)O(1) (on average) for each operation.

Constraints:

  • 231-2^{31} \leq data 231\leq 2^{31}
  • No more than 2×1052 \times 10^5 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)

1.

What is the output for the following series of commands?

Delete(20), Insert(20), Insert(20), GetRandom()
A.

FALSE, TRUE, TRUE, 20

B.

FALSE, TRUE, FALSE, 20

C.

TRUE, TRUE, TRUE, 20

D.

FALSE, FALSE, TRUE, 20


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks required to implement the Delete operation.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in the following coding playground.

Go
usercode > random_set.go
package main
type RandomSet struct {
// Write your code here
}
func Init() *RandomSet {
// Replace this placeholder return statement with your code
return new(RandomSet)
}
/*
Inserts a value in the data structure.
Returns True if it did not already contain the specified element.
*/
func (up *RandomSet) Insert(val int) bool {
// Replace this placeholder return statement with your code
return false
}
/*
Removes a value from the data structure.
Returns True if it contained the specified element.
*/
func (up *RandomSet) Delete(val int) bool {
// Replace this placeholder return statement with your code
return false
}
/*
Choose an element at random from the data structure.
*/
func (up *RandomSet) GetRandom() int {
// Replace this placeholder return statement with your code
return -1
}
Insert Delete GetRandom O(1)

Access this course and 1200+ top-rated courses and projects.