Design a Song Randomizer Avoiding Recent Repeats

viaGlassdoor

Problem: Design a function to pick a random song from a playlist of n songs such that none of the last 20 played songs can be picked again.

Constraints: Should support repeated calls efficiently as playback continues; n can be much larger or comparable to 20.

Example: Playlist of 30 songs; after playing songs [3,7,12,...] (20 most recent), the next random pick must exclude those 20 indices.

Approach: Maintain the 'excluded' set as a fixed-size sliding window (e.g., a queue/deque of the last 20 played indices plus a hash set for O(1) membership checks). One approach: maintain an active pool of eligible songs; when a song is played, move it to the back of the recently-played queue and remove it from the eligible pool; when the queue exceeds 20, pop the oldest and return it to the eligible pool. Pick uniformly at random from the eligible pool (e.g., via an array-backed set supporting O(1) random access, similar to the 'RandomizedSet' pattern) for O(1) amortized selection.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account