Number of Music Playlists - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: n = 3, goal = 3, k = 1
Output: 6
💡 Note: We have 3 songs and want a playlist of length 3. Each song must be played at least once, and we can't repeat a song until 1 other song has been played. Possible playlists: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1].
Example 2 — Higher K Value
$ Input: n = 2, goal = 3, k = 0
Output: 6
💡 Note: With k=0, we can repeat any song immediately. We have 2 songs, need length 3, both songs used at least once. Playlists: [1,1,2], [1,2,1], [1,2,2], [2,1,1], [2,1,2], [2,2,1].
Example 3 — Impossible Case
$ Input: n = 2, goal = 3, k = 3
Output: 0
💡 Note: With k=3, we need to play 3 other songs before repeating. But we only have 2 songs total, so it's impossible to repeat any song in a playlist of length 3.

Constraints

  • 1 ≤ n ≤ 100
  • 1 ≤ goal ≤ 100
  • 0 ≤ k < n

Visualization

Tap to expand
Number of Music Playlists INPUT S1 S2 S3 n = 3 different songs ? ? ? goal = 3 slots to fill Parameters: n = 3 goal = 3 k = 1 (cooldown) ALGORITHM (DP) 1 Define State dp[i][j] = playlists of length i with j songs 2 Add New Song dp[i][j] += dp[i-1][j-1] * (n - j + 1) 3 Replay Old Song dp[i][j] += dp[i-1][j] * max(0, j - k) 4 Return Result Answer = dp[goal][n] mod 10^9 + 7 DP Table (simplified) j 1 2 3 3 0 0 6 FINAL RESULT All 6 Valid Playlists: [S1, S2, S3] [S1, S3, S2] [S2, S1, S3] [S2, S3, S1] [S3, S1, S2] [S3, S2, S1] OUTPUT 6 Key Insight: The DP state dp[i][j] counts playlists of length i using exactly j unique songs. For each position, we can either add a NEW song (n-j+1 choices) or REPLAY an old song (j-k choices if j > k). The cooldown k ensures variety by preventing immediate repeats. Final answer: dp[goal][n]. TutorialsPoint - Number of Music Playlists | Dynamic Programming Approach
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
28.5K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen