Sample a Random Pending Review With Constant-Time Insert and Delete

Last updated: November 29, 2026

Quick Overview

Design a structure for the review moderation queue that supports insert(id), remove(id) and get_random(), each in average O(1) time, where get_random returns each present review ID with equal probability.

Amazon
Coding & Algorithms
Software Engineer
Amazon
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


Design a structure for the review moderation queue that supports insert(id), remove(id) and get_random(), each in average O(1) time, where get_random returns each present review ID with equal probability.

Used in Amazon onsites as a data structure design problem around sampling customer reviews for human audit. The interviewer probes whether you combine an array with a value-to-index map and handle removal by swapping with the last element.

What the Interviewer Expects
  • Explain why a set alone cannot sample uniformly in O(1)
  • Pair a list for sampling with a dict from id to index
  • Delete by swapping with the last element and popping
  • Update the moved element's index correctly
  • Return booleans for duplicate inserts and missing removes
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 duplicate IDs (a multiset) with the same guarantees?
  • How would you sample weighted by how many reports each review has?
  • What changes to make this thread safe for many moderators?
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

Operations: insert(id) returns True if newly added, remove(id) returns True if it was present, get_random() returns a uniformly random present id (called only when non-empty). All average O(1)....

High-Level Design

A Python list gives O(1) random access, so random.choice is uniform and fast, but removing from the middle is O(n). A dictionary mapping id to its list index fixes that: to remove an id, copy the la...


Submit Your Answer
Markdown supported