Google Interview experience
1 round over 2 weeks. No offer, meh experience.
I was asked this question during the phone screen round
Problem Statement:
Given a list of songs and an integer k that represents the cooldown period, write a shuffle function for a music player that returns a random song from the list. The function should ensure that no song is played again until at least k other songs have been played.
Example:
songs = [A, B, C] and k = 2
shuffle([A, B, C]) -> B
shuffle([A, _, C]) -> C
shuffle([A, _, _]) -> A
shuffle([_, B, _]) -> B # B is eligible again as 2 songs have been played since it was last selectedClarifying questions that I asked:
What if k is greater than the total number of songs? can ignore the cooldown period and replay a song
Possible Approach:
We can keep a queue of size k for the songs we've played. When we play a song, add it to the back of the queue. If the queue gets bigger than k, pop the oldest song from the front and put it back in the list so it can be picked again later.
def shuffle(songs, k):
played_queue = deque()
while True:
eligible_songs = [song for song in songs if song not in played_queue]
if not eligible_songs:
break # if no eligible songs are left
next_song = random.choice(eligible_songs)
print("Playing:", next_song)
# Add the played song to the queue
played_queue.append(next_song)
# If the queue exceeds size k, remove the oldest song from the queue
if len(played_queue) > k:
played_queue.popleft()
Know someone interviewing at Google? Pass it on.
Same company, different candidates.
Share yours while it’s fresh. It takes five minutes, it’s anonymous, and it will help future candidates.