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
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

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
Hash map
Dynamic array
Randomization
Data structure design
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample Answer
Requirements
  • insert(v) returns True if v was new.
  • remove(v) returns True if v was 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...


Submit Your Answer
Markdown supported