Design a no-repeat top-frequency music player
AmazonSoftware Engineer · OnsiteLast updated
Design a no-repeat frequency-based music player with addUserSongs and getNextSong APIs. Covers max-heap data structures, lazy deletion, cycle resets, mid-cycle song additions, and complexity.
Design and implement a music player that receives song lists from new users and returns songs to play in frequency order without repeating a song in the same cycle.
The system supports two APIs:
addUserSongs(userId, songs): a new user arrives with a list of song IDs. Each appearance of a song increases that song's global frequency by 1.getNextSong(): returns the next song ID to play.
Playback rules:
- Among songs that have not yet been played in the current cycle, choose the song with the highest global frequency.
- A song cannot be replayed within the same cycle.
- Once every known song has been played once in the current cycle, the next selection starts a new cycle and all known songs are eligible again.
- New songs can arrive at any time and should be eligible in the active cycle unless that song has already been played in that cycle.
Constraints & Assumptions
- Song IDs may be strings or integers.
- The same song may appear multiple times in one user's list, and each appearance counts.
- If multiple songs tie on frequency, any deterministic or arbitrary tie-break is acceptable if you state it.
- Assume up to
100000total song additions and100000getNextSong()calls. - Returning
Noneor raising an empty-state exception is acceptable when no songs are known; state your choice.
Clarifying Questions to Ask
- Should ties be deterministic, such as lexicographic order, or is arbitrary order acceptable?
- Do song frequencies ever decay or get deleted, or only increase?
- Should a user's songs be deduplicated per user or counted by every appearance?
- Is the system single-threaded for the interview implementation, or do we need concurrency controls?
Follow-up questions
- How would you make the implementation thread-safe?
- How would you support deleting a song or decreasing its frequency?
- How would you shard this if the catalog were too large for one machine?
- What changes if tie-breaking must be stable across restarts?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.