Insert Delete GetRandom O(1)

Implement RandomizedSet: insert(val) adds val if absent and returns true, otherwise false; remove(val) removes val if present and returns true, otherwise false; getRandom() returns a uniformly random element (at least one element is present). Every operation must run in average O(1) time. Here getRandom is only called when the set holds exactly one element, so the output is deterministic.

30:00

Insert Delete GetRandom O(1)
medium
Free written solution
Topics
Companies

Implement RandomizedSet: insert(val) adds val if absent and returns true, otherwise false; remove(val) removes val if present and returns true, otherwise false; getRandom() returns a uniformly random element (at least one element is present). Every operation must run in average O(1) time. Here getRandom is only called when the set holds exactly one element, so the output is deterministic.

Example 1:
Input: {"commands":["RandomizedSet","insert","remove","insert","remove","getRandom","insert","getRandom"],"values":[[],[1],[2],[2],[1],[],[2],[]]}
Output: [null,true,false,true,true,2,false,2]
Constraints:
  • −231≤val≤231−1-2^{31} \leq \text{val} \leq 2^{31} - 1

  • At most 2×1052 \times 10^5 calls will be made to insert, remove, and getRandom.

  • There will be at least one element in the data structure when getRandom is called.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"commands":["RandomizedSet","insert","remove","insert","remove","getRandom","insert","getRandom"],"values":[[],[1],[2],[2],[1],[],[2],[]]}

Create an empty array of values and an empty hash map from each value to its index in the array.

RandomizedSet

op 0/7, size 0

vals (array, random access by index)

0

pos (hash map, value -> index)

empty

output

[null]

slot touched
last value moved into the hole
removed value
map entry touched
Removing swaps the last value into the hole, so the array never shifts.
Variables
VariableValue
size0
DepthFunction Call
Stack empty
0/15