Number Of Music Playlists Problem
Description
LeetCode Problem 920.
Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that:
- Every song is played at least once.
- A song can only be played again only if k other songs have been played.
Given n, goal, and k, return the number of possible playlists that you can create. Since the answer can be very large, return it modulo 10^9 + 7.
Example 1:
Input: n = 3, goal = 3, k = 1
Output: 6
Explanation: There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1].
Example 2:
Input: n = 2, goal = 3, k = 0
Output: 6
Explanation: There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2].
Example 3:
Input: n = 2, goal = 3, k = 1
Output: 2
Explanation: There are 2 possible playlists: [1, 2, 1] and [2, 1, 2].
Constraints:
- 0 <= k < n <= goal <= 100
Solution
Approach: Dynamic Programming on Length and Distinct Songs
Build the playlist one song at a time. What matters for the next choice is only how many different songs have been used so far. Let ways[i][j] be the number of playlists of length i that use exactly j different songs. The answer is ways[goal][n].
The i-th song is either new or a replay:
- New song. Before it, the playlist had
j - 1different songs, so there aren - (j - 1)unused songs to pick from:ways[i-1][j-1] · (n - j + 1). - Replay. The playlist already had
jdifferent songs. The lastksongs played are all different (no song can repeat withink), so exactlykof thejsongs are blocked andj - kcan be replayed:ways[i-1][j] · max(j - k, 0).
So ways[i][j] = ways[i-1][j-1] · (n - j + 1) + ways[i-1][j] · max(j - k, 0), taken modulo 109 + 7, starting from ways[0][0] = 1.
The step people get wrong is the replay count. It is j - k because the last k songs are guaranteed to be distinct and all among the j used songs; this only holds when j > k, which is why the factor is clamped at 0. Also take the modulo after every step, and use 64-bit integers for the products.
Example: n = 2, goal = 3, k = 1. ways[1][1] = 2, ways[2][2] = 2 · 1 = 2, and ways[3][2] = ways[2][1] · 1 + ways[2][2] · (2 - 1) = 0 + 2 = 2.
Complexity: O(goal · n) time and O(goal · n) space.
class Solution:
def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:
MOD = 10 ** 9 + 7
# ways[i][j] = playlists of length i that use exactly j different songs
ways = [[0] * (n + 1) for _ in range(goal + 1)]
ways[0][0] = 1
for i in range(1, goal + 1):
for j in range(1, n + 1):
# The i-th song is new: any of the n - (j - 1) songs not used yet.
new_song = ways[i - 1][j - 1] * (n - (j - 1))
# The i-th song is a replay: any used song except the last k played.
replay = ways[i - 1][j] * max(j - k, 0)
ways[i][j] = (new_song + replay) % MOD
return ways[goal][n]
Now write it from memory
Close the write-up and solve it yourself against the tests.