#K69227. Randomized Set Implementation
Randomized Set Implementation
Randomized Set Implementation
This problem requires you to design a data structure RandomizedSet that supports the following operations in O(1) average time:
insert(value)
: Inserts an integer value into the set if it is not already present. Returnstrue
if the insertion was successful, otherwisefalse
.remove(value)
: Removes an integer value from the set if it exists. Returnstrue
if the removal was successful, otherwisefalse
.getRandom()
: Returns a random element from the current set of elements. It is guaranteed that the set is non-empty when this method is called and the returned element is chosen uniformly at random.
Note: All inserted values will be in the range \(1 \leq value \leq 2 \times 10^5\).
You will be given a sequence of operations. The first line of the input contains a single integer n representing the number of operations. Each of the next n lines contains an operation in one of the following formats:
insert x
, remove x
or getRandom
For every operation, output its result on a new line. For insert
and remove
, print true
or false
(all lowercase) depending on the operation's success. For getRandom
, print the integer returned.
inputFormat
The first line contains an integer n (n \(\geq\) 1) representing the number of operations.
Each of the following n lines contains one of the three commands:
insert x
— insert the integer x into the set.remove x
— remove the integer x from the set.getRandom
— get a random integer from the current set.
It is guaranteed that getRandom
will only be called when the set is non-empty.
outputFormat
For each operation, output the result on a new line. For insert
and remove
, output true
or false
. For getRandom
, output the integer returned by the operation.
4
insert 1
insert 2
remove 2
getRandom
true
true
true
1
</p>