Insert Delete GetRandom O(1)
MediumArrays & Hashing
Decode it first. Clues, constraints, pattern and plan before any code.Build a class RandomizedSet that stores distinct integers and supports three operations, each in average O(1) time:
insert(val): addvalif it is not already present. Returntrueif it was added,falseif it was already there.remove(val): deletevalif present. Returntrueif it was removed,falseif it was not there.get_random()(getRandomin TypeScript): return a random current element, where every element is equally likely.
s = RandomizedSet()
s.insert(1) → true
s.remove(2) → false
s.insert(2) → true
s.get_random() → 1 or 2
s.remove(1) → true
s.get_random() → 2 (the only element left)Constraints
-2^31 <= val <= 2^31 - 1- At most
2 * 10^5calls in total. get_randomis only called when the set is not empty.