KatInterview

Frequency-Ranked Shuffle Without Repeats Per Round

Data Structure DesignModel answer
MediumModel answerData Structure Designheaplazy-deletionhash-map

Last updated

Build a player that ingests users' song lists and serves songs from most to least popular, never repeating a song until every known song has played once in the round.

Build an in-memory player that gathers songs from users and plays them in order of popularity, without repeating a song until every known song has been played once.

The player exposes two operations:

  • addUserSongs(userId, songs): a user joins with a list of song IDs. Every occurrence of a song adds 1 to that song's global popularity count, including repeated occurrences within the same list.
  • getNextSong(): returns the ID of the next song to play.

Selection rules

  1. Among songs not yet played in the current round, pick the one with the highest global count.
  2. A song is never played twice in the same round.
  3. When all known songs have been played in the round, the next call to getNextSong() starts a fresh round in which every known song is eligible again.
  4. Users can join at any time. A song first seen mid-round is eligible in that round, unless it has already been played in it. Counts keep increasing mid-round and affect later picks.

Assumptions

  • Song IDs are strings or integers.
  • Counts only grow; nothing decays or is removed.
  • Ties may be broken arbitrarily, but you must state your rule.
  • Up to 100,000 total song occurrences and 100,000 getNextSong() calls.
  • If no songs are known, return None (or raise an error), and state which.
  • Single-threaded is fine.

What to deliver

Describe your data structures, implement both operations, explain how rounds reset and how mid-round arrivals are handled, and give the time and space complexity. Mention which clarifying questions you would ask.

Hints

Hint 1

Keep a hash map from song to global count and a set of songs already played in the current round. The question is how to get the best unplayed song quickly while counts keep changing.

Hint 2

A max-heap cannot cheaply update an existing key. Push a fresh entry every time a song's count changes (if the song is still eligible), and when popping, discard entries that are stale (count no longer matches) or whose song was already played.

Hint 3

A round ends when the played set is the same size as the set of known songs. Rebuilding the heap from the count map at that moment costs O(U), but a round contains at least U plays, so the rebuild is amortized O(1) per call.