Music player that plays the most frequent unplayed song
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's coding round, last asked Mar 2025. It tests heap, hashing and streaming.
Build a music player fed by users who keep arriving with song lists. Every appearance of a song in a list adds one to that song's global count. The player always plays the most frequent song that has not been played yet in the current cycle. A song cannot repeat within a cycle; once every known song has played, a new cycle starts and all songs are eligible again. Songs added in the middle of a cycle can play in that cycle unless they already did.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
add_user_songs(user_id: str, songs: list[str]) -> None— each appearance adds 1 to that song's count, including repeats in the same list. -
get_next_song() -> str | None— the unplayed song with the highest count, ties broken by the smaller song id;Nonewhen no songs are known.
Example
add_user_songs("u1", ["a", "b", "a"]) # a = 2, b = 1
get_next_song() -> "a"
add_user_songs("u2", ["b", "b", "c"]) # a = 2, b = 3, c = 1
get_next_song() -> "b"
get_next_song() -> "c" # a already played this cycle
get_next_song() -> "b" # every song played: new cycle
get_next_song() -> "a"
Constraints
- Up to 100,000 song additions and 100,000
get_next_songcalls. - Counts only go up.
Clarifying questions
- Should ties be broken deterministically? By id, or by first appearance?
- Do repeats in one user's list count once or every time?
- Can counts ever drop, or songs be removed?
- Single-threaded, or do calls arrive concurrently?
What a strong answer covers
- A count map, a set of songs played this cycle, and a max-heap of
(-count, song_id)entries with lazy deletion: stale entries (old counts, already played) are skipped when popped. - Pushing a fresh entry whenever a count changes, so the heap stays correct without decrease-key.
- The cycle reset: rebuild the heap from all known songs in O(S); amortised O(log S) per call.
- Songs added mid-cycle going straight into the heap; tests for ties, a new song mid-cycle and an empty player.
Follow-ups
- Make it thread-safe. Where are the locks, and what about a reset racing an add?
- Support deleting a song or lowering its count.
- The catalog no longer fits on one machine. How would you shard it?
- Tie-breaks must stay stable across restarts. What do you persist?
Where it's asked
- Amazon · Coding · Last asked Mar 202555 min · Usually two rounds; one is often an object-oriented design built in steps · No AI
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
