#K57417. Design a Randomized Set Supporting Insert, Delete, and GetRandomElement Operations
Design a Randomized Set Supporting Insert, Delete, and GetRandomElement Operations
Design a Randomized Set Supporting Insert, Delete, and GetRandomElement Operations
You are required to design a data structure RandomizedSet
that supports the following operations in average O(1) time complexity:
- insert: Insert an integer val into the set. Returns
True
if the element was not already present, andFalse
otherwise. - delete: Remove an integer val from the set. Returns
True
if the element was present, andFalse
otherwise. - getRandomElement: Return a random element from the current set of elements. It is guaranteed that at least one element exists when this operation is called and each element must have the same probability of being chosen.
Note: To ensure reproducible results, you must seed the random number generator with 0 at the beginning of your program. In other words, if multiple elements are present when getRandomElement
is called, the selection should be determined by the generator seeded with 0. Formally, the time complexity requirement is $O(1)$ on average for each operation.
inputFormat
The input is read from standard input (stdin) and is formatted as follows:
- An integer
n
denoting the number of operations. - Next
n
lines, each line represents a command, which can be one of the following:insert x
: Insert the integerx
into the set.delete x
: Delete the integerx
from the set.getRandomElement
: Get a random element from the set.
It is guaranteed that every getRandomElement
command is called when the set is non-empty.
outputFormat
For each operation provided in the input, output the result on a separate line to standard output (stdout):
- For
insert
anddelete
operations, outputTrue
orFalse
(case-sensitive) depending on the success of the operation. - For
getRandomElement
operations, output the integer value returned.
6
insert 1
insert 2
insert 1
getRandomElement
delete 2
getRandomElement
True
True
False
2
True
1
</p>