Frequency-Ranked Shuffle Without Repeats Per Round
Data Structure DesignModel answerLast 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
- Among songs not yet played in the current round, pick the one with the highest global count.
- A song is never played twice in the same round.
- 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. - 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying questions
- Are ties broken deterministically? I will use first-seen order (earliest first-seen song wins), which also avoids comparing mixed
str/intIDs. - Do counts ever decrease? I assume not.
- Is each occurrence counted, even repeats inside one user's list? Yes, per the statement.
- Single-threaded? I assume so. Otherwise I would put a lock around both operations.
- Empty state: I return
None.
Core idea
Maintain three pieces of state:
count[song]: global count.played: set of songs already played in the current round.- A max-heap of entries
(-count, firstSeenIndex, song), using lazy deletion.
Heaps do not support efficient "increase key" on arbitrary elements. Instead of updating an entry, I push a new one with the new count and let the old one go stale. An entry is valid only if both of these hold:
- The song is not in
played. - The entry's count equals
count[song]right now.
Stale entries are thrown away when they reach the top.
Operations
addUserSongs: for each song occurrence, increment count[song]. If the song is new, record its first-seen index. If the song is not in played, push (-count, index, song). If it has already been played this round, only the count changes, because it cannot be chosen again until the next round. The reset rebuilds the heap from count, so nothing is lost. userId is not needed for the logic, though you could store it if you wanted per-user features.
getNextSong:
- If there are no known songs, return
None. - If
len(played) == len(count), the round is complete. Clearplayedand rebuild the heap from every song's current count, thenheapify. - Pop until a valid entry is found, mark that song as played, and return it.
Invariant: every unplayed song has at least one heap entry carrying its latest count. This holds because we push on every change to an unplayed song and rebuild at each reset. So if len(played) < len(count), step 3 always finds a valid entry.
Code
import heapq
class MusicPlayer:
def __init__(self):
self.count = {}
self.order = {} # first-seen index, used as tie-break
self.played = set()
self.heap = []
def add_user_songs(self, user_id, songs):
for s in songs:
if s not in self.count:
self.count[s] = 0
self.order[s] = len(self.order)
self.count[s] += 1
if s not in self.played:
heapq.heappush(self.heap, (-self.count[s], self.order[s], s))
def get_next_song(self):
if not self.count:
return None
if len(self.played) == len(self.count):
self.played.clear()
self.heap = [(-c, self.order[s], s) for s, c in self.count.items()]
heapq.heapify(self.heap)
while self.heap:
neg, _, s = heapq.heappop(self.heap)
if s in self.played or -neg != self.count[s]:
continue # stale entry
self.played.add(s)
return s
Walkthrough
Users add [a, a, b] and [b, c]. Counts are a=2, b=2, c=1. Round 1 plays a (tie with b, earlier first-seen), then b. Now a user adds [c, c, c, a]. The count of a becomes 3, but a is already played, so no push. c becomes 4 and is pushed. The next call returns c. The round is now complete, so the following call resets and plays c first (4), then a (3), then b (2).
Complexity
- addUserSongs: O(k log H) for k occurrences, where H is the heap size.
- getNextSong: O(log H) per pop, with amortized O(1) pops of stale entries per call, because each pushed entry is popped at most once.
- Reset: O(U) for U distinct songs. A round only ends after all U songs were played, which took at least U calls, so the reset is amortized O(1) per call.
- Total: O((A + G) log(A + G)) for A additions and G gets, well within 100k limits.
- Space: O(U) for the maps plus the heap, which can reach O(A + U) entries before stale ones are drained. If memory matters, rebuild the heap when stale entries exceed about twice the live ones.
Trade-offs and alternatives
- A balanced BST or sorted container keyed by
(count, order)supports true decrease/increase-key and avoids stale entries, at the cost of heavier code and a bigger constant. In Python there is no built-in one. - A bucket-by-count structure works well when counts only increase by 1, but a user's list can bump a song several times, and finding the max non-empty bucket needs extra bookkeeping.
- Lazy deletion is the simplest option with good amortized bounds.
Common mistakes
- Pushing an entry for a song that was already played this round. It then gets replayed, or at least needs an extra check.
- Forgetting the stale-count check, which causes songs to be served at an outdated rank.
- Resetting the played set but not rebuilding the heap. The old heap has had entries popped, so many songs would be missing.
- Declaring a round finished when the heap is empty rather than when
playedcovers all known songs. A heap can also be empty of valid entries for other reasons if the invariant is broken. - Comparing mixed-type IDs in heap tuples. The integer first-seen index prevents this.
- Not handling the empty case, where
getNextSong()is called before any songs are added.