Insert Delete GetRandom O(1)

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Implement the RandomizedSet class that supports the following operations in average O(1) time complexity:

  • "RandomizedSet" — Initializes the RandomizedSet object.
  • "insert" — Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
  • "remove" — Removes an item val from the set if present. Returns true if the item was present, false otherwise.
  • "getRandom" — Returns a random element from the current set of elements. Each element must have the same probability of being returned.

You are given an array of operations and an array of arguments and must return the result of each operation.

Examples

Example 1:

Input: operations = ["RandomizedSet","insert","remove","insert","getRandom","remove","insert","getRandom"], args = [[],[1],[2],[2],[],[1],[2],[]]

Output: [null,true,false,true,2,true,false,2]

Explanation: Initialize an empty set. Insert 1 (returns true). Remove 2 (returns false, not present). Insert 2 (returns true). getRandom returns either 1 or 2. Remove 1 (returns true). Insert 2 (returns false, already present). getRandom returns 2.

Example 2:

Input: operations = ["RandomizedSet","insert","insert","insert","getRandom","getRandom","getRandom"], args = [[],[1],[2],[3],[],[],[]]

Output: [null,true,true,true,1,2,3]

Explanation: After inserting 1, 2, and 3, getRandom returns any of the three elements with equal probability. The expected output shows one possible sequence.

Constraints

  • -2^31 <= val <= 2^31 - 1
  • At most 2 * 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
Source: Hash Maps pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle