Number of Music Playlists - Problem
Create Perfect Music Playlists
You have a music library with
๐ต Rule 1: Every song must be played at least once
๐ Rule 2: A song can only be repeated after
For example, if
Your task: Count how many different valid playlists you can create. Since this number can be astronomically large, return the result modulo
You have a music library with
n different songs and want to create a playlist of exactly goal songs for your road trip. But there's a catch - you want to avoid repetitive listening while ensuring variety:๐ต Rule 1: Every song must be played at least once
๐ Rule 2: A song can only be repeated after
k other different songs have been playedFor example, if
k=2 and you play song A, you must play 2 other different songs before you can play song A again.Your task: Count how many different valid playlists you can create. Since this number can be astronomically large, return the result modulo
109 + 7. Input & Output
example_1.py โ Basic Case
$
Input:
n=3, goal=3, k=1
โบ
Output:
6
๐ก Note:
With 3 songs and goal of 3, we must use each song exactly once. There are 3! = 6 permutations: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]. Since k=1, no repetitions are allowed anyway.
example_2.py โ With Repetition
$
Input:
n=2, goal=3, k=0
โบ
Output:
6
๐ก Note:
With k=0, we can repeat songs immediately. Valid playlists: [1,1,2], [1,2,1], [1,2,2], [2,1,1], [2,1,2], [2,2,1]. Each uses both songs at least once.
example_3.py โ Gap Constraint
$
Input:
n=2, goal=3, k=1
โบ
Output:
2
๐ก Note:
With k=1, we need 1 different song between repetitions. Valid playlists are [1,2,1] and [2,1,2]. Playlists like [1,1,2] are invalid because the two 1's are adjacent.
Visualization
Tap to expand
Understanding the Visualization
1
Empty Playlist
Start with no songs played (dp[0][0] = 1)
2
Add First Song
Choose any of n songs for first position
3
Branching Decisions
At each position, decide: new song or repeat old song?
4
Apply Constraints
New song only if j < n; repeat only if j > k
5
Final Count
Sum all ways to reach goal length with all n songs used
Key Takeaway
๐ฏ Key Insight: At each step, we have exactly two choices: introduce a new song (if available) or repeat an old song (if the k-gap constraint allows it). Dynamic programming efficiently counts all valid combinations.
Time & Space Complexity
Time Complexity
O(goal ร n)
We fill a 2D DP table of size goal ร n, each cell computed in O(1)
โ Linear Growth
Space Complexity
O(goal ร n)
DP table stores goal ร n states, can be optimized to O(n) with rolling array
โก Linearithmic Space
Constraints
- 1 โค n โค 100
- 1 โค goal โค 100
- 0 โค k < n
- goal โฅ n (must be able to play all songs at least once)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code