Design a Shuffle Pool With Constant-Time Insert, Remove and Random Pick

Last updated: November 29, 2026

Quick Overview

Apple Music's shuffle needs a pool of track ids supporting insert(id), remove(id) and pick_random(), each in average O(1) time, where pick_random returns every current track with equal probability.

Apple
Coding & Algorithms
Software Engineer
Apple
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Apple Music's shuffle needs a pool of track ids supporting insert(id), remove(id) and pick_random(), each in average O(1) time, where pick_random returns every current track with equal probability.

A data structure design question that Apple uses to test whether candidates can combine two structures to get each operation's best cost. The interviewer looks for the array plus index-map trick and correct swap-with-last removal.

What the Interviewer Expects
  • Use an array for O(1) random access and a dict from id to index
  • Remove by swapping the target with the last element and popping
  • Update the moved element's index in the map
  • Return booleans for duplicate inserts and missing removes
  • Explain why a set alone cannot support uniform random pick in O(1)
Key Topics to Cover
hash maps
arrays
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
  • Allow duplicates so a track can appear multiple times with proportional probability.
  • Never repeat a track until all others have played; how do you implement that?
  • Weight tracks by user affinity instead of uniform choice.
  • Make the structure safe for concurrent access from playback and UI threads.
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) adds and returns True, or False if present. remove(id) deletes and returns True, or False if absent. pick_random() returns a uniformly random present id, raising on an emp...

High-Level Design

Keep items, a Python list of ids, and pos, a dict from id to its index in the list. Insert appends and records the index. Remove looks up the index, moves the last element into that slot, updates ...


Submit Your Answer
Markdown supported