Insert Delete GetRandom O(1)
MediumP2Coding
Design a set of integers that supports insert, delete and picking a random element, all in O(1) average time.
Implement the RandomizedSet class:
RandomizedSet()creates an empty set.insert(val)addsvaland returnstrue, or returnsfalseif it was already present.remove(val)removesvaland returnstrue, or returnsfalseif it was not present.getRandom()returns a uniformly random element of the current set. It is only called when the set is not empty.contains(val)andsize()report membership and the number of elements (added so the tests can check state).
Random output cannot be compared exactly, so the tests call getRandom() only when the set holds exactly one element.
Example 1
- Input
- ["RandomizedSet","insert","remove","insert","size","remove","getRandom"] [[],[1],[2],[2],[],[1],[]]
- Output
- [null,true,false,true,2,true,2]
- Why
- With one element left, getRandom must return it.
Constraints
- -2^31 <= val <= 2^31 - 1
- At most 2 * 10^5 calls.
- getRandom is only called on a non-empty set.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 2 visible tests, Submit all 7. ⌘Enter runs, ⌘⇧Enter submits.