Skip to main content
Back to problems
#920
Hard Algorithms

Number of music playlists

Math Dynamic Programming Combinatorics
60.0% acceptance
Feb 25, 2026
2462
206
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 109 + 7.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn num_music_playlists(n: i32, goal: i32, k: i32) -> i32 {
    let md = 1_000_000_007i64;
    let (n, goal, k) = (n as usize, goal as usize, k as usize);
    let mut dp = vec![vec![0i64; n + 1]; goal + 1];
    dp[0][0] = 1;
    for i in 1..=goal {
      for j in 1..=n {
        dp[i][j] = (dp[i][j] + dp[i-1][j-1] * (n - (j - 1)) as i64) % md;
        if j > k { dp[i][j] = (dp[i][j] + dp[i-1][j] * (j - k) as i64) % md; }
      }
    }
    dp[goal][n] as i32
  }
}