230. Insert Delete GetRandom O(1)

MediumDesign

Implement the RandomizedSet class supporting average O(1) time for each operation: RandomizedSet() initializes the object; insert(val) inserts val if not present and returns true, otherwise returns false; remove(val) removes val if present and returns true, otherwise returns false; getRandom() returns a random element from the current set (each element equally likely). At least one element exists when getRandom is called. Note: in this catalog the getRandom calls are set up so exactly one element is present, making the expected output deterministic.

Examples

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

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

Explanation: getRandom is queried only when a single element remains, so its result is deterministic.

Constraints

  • -2^31 <= val <= 2^31 - 1; at most 2 * 10^5 calls to insert, remove, and getRandom; there will be at least one element when getRandom is called
Loading...

Run checks all cases above. Submit evaluates all test cases.