Candidate Pool With Constant-Time Insert, Remove and Random Pick
Last updated: November 29, 2026
Quick Overview
Design a set of candidate post ids that supports insert, remove and get_random, each in average O(1) time, where get_random returns every current element with equal probability.
Meta
November 29, 20260
0
0 solved
Design a set of candidate post ids that supports insert, remove and get_random, each in average O(1) time, where get_random returns every current element with equal probability.
Exploration slots in Feed ranking occasionally show a uniformly random candidate, so the pool must stay sampleable while it churns. This is one of the most common Meta design-a-structure questions; the interviewer is checking the swap-with-last trick and the index bookkeeping.
What the Interviewer Expects
- Explain why a hash set alone cannot sample uniformly in O(1)
- Combine a dynamic array with a value-to-index map
- Remove by swapping the target with the last element
- Update the moved element's index correctly
- Handle removal of the last element without a stale index
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you support duplicates, where get_random is weighted by count?
- How would you sample k distinct elements at once?
- What if elements carry weights and sampling must be proportional to weight?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
insert(v)returns True ifvwas new.remove(v)returns True ifvwas present.get_random()is called only on a non-empty pool and must be uniform....
High-Level Design
Keep elements densely packed in a list so random.choice is O(1) and uniform. A dict maps each value to its list index. To remove from the middle without shifting, move the last element into the vaca...