Insert Delete GetRandom O(1)
Design a set that supports insert(val), remove(val), and getRandom, each in average O(1) time. insert returns false if val is already present, true otherwise. remove returns false if val is absent, true otherwise. getRandom returns a uniformly random element currently in the set.
Open official problem prompt ↗Build a container where adding, removing, and picking a uniformly random element are all constant time on average.
Think of a coat-check rack: the numbered hooks (the list) let you grab a random coat instantly, and a ledger mapping each ticket to its hook number (the map) lets you find any specific coat. When someone leaves, you move the last coat onto their freed hook rather than sliding every coat down.
- Input
- insert(1); remove(2); insert(2); getRandom(); remove(1); insert(2); getRandom()
- Output
- [true, false, true, 2, true, false, 2]
- Why
- insert(1) succeeds; remove(2) fails (absent); insert(2) succeeds; the set is {1,2} so getRandom returns 1 or 2; remove(1) succeeds; insert(2) fails (present); the set is {2} so getRandom must return 2.
-2^31 <= val <= 2^31 - 1At most 2 * 10^5 calls total to insert, remove, and getRandomgetRandom is only called when the set has at least one element