Hi,
The following question was asked to me during my recent google onsite round.
Problem Statement:
Given a playlist of songs, you have to design a song shuffler.
This song shuffler is not like the normal song shuffler that shuffles the complete playlist at the start and returns a shuffled list, but instead when asked for a next song to be played, returns a random song from the list of songs.
The next random song to be played should satisfy a condition that the song was not played in the last 'k' turns.
You have to make sure, that at each call, all the eligible (not played during last k turns) songs have equal probability of being played next.
For example:
if songs = [A, B, C, D], k = 2,
then a possible random sequence of songs can be:
playNext: [ A , B , C , D ] -> return C
playNext: [ A , B , _ , D ] -> return A
playNext: [ _ , B , _ , D ] -> return B
playNext: [ _ , _ , C , D ] -> return C (as C was not played in the last two turns, it has an equal probability with D to be played).Thanks