AAmazon·DSASDE-2Onsite – Coding 2
RandomizedSet — Insert, Delete, GetRandom in O(1)
Problem
Design a data structure that supports:
insert(val)— inserts val if not present, returns true/falseremove(val)— removes val if present, returns true/falsegetRandom()— returns a random element with equal probability
All three must run in average O(1) time.
Constraints
- -2^31 ≤ val ≤ 2^31 - 1
- Up to 2 × 10^5 calls
- getRandom is called only when at least one element exists
Hint
Think about what combination of data structures gives you O(1) for all three operations.
asked 5 days ago
Follow-up questions (0)
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.