HardNo. 0920
Number of Music Playlists — LeetCode 920 Python Solution
- Pattern
- Dynamic Programming
- Topics
- Math, Dynamic Programming, Combinatorics
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip.
Example
- 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].
Python solution
class Solution:
def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:
mod = 10**9 + 7
f = [[0] * (n + 1) for _ in range(goal + 1)]
f[0][0] = 1
for i in range(1, goal + 1):
for j in range(1, n + 1):
f[i][j] = f[i - 1][j - 1] * (n - j + 1)
if j > k:
f[i][j] += f[i - 1][j] * (j - k)
f[i][j] %= mod
return f[goal][n]Complexity
- Time
- O(goal × n)
- Space · auxiliary
- O(goal × n)
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 920. Number of Music Playlists is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0062 | Unique Paths | Medium |
| 0458 | Poor Pigs | Hard |
| 1359 | Count All Valid Pickup and Delivery Options | Hard |
| 1467 | Probability of a Two Boxes Having The Same Number of Distinct Balls | Hard |
| 1569 | Number of Ways to Reorder Array to Get Same BST | Hard |
| 1621 | Number of Sets of K Non-Overlapping Line Segments | Medium |
Frequently asked questions
- How hard is LeetCode 920. Number of Music Playlists?
LeetCode 920. Number of Music Playlists is rated Hard on LeetCode.
- What is the time complexity of LeetCode 920. Number of Music Playlists?
The Python solution on this page runs in O(goal × n).
- What is the space complexity of LeetCode 920. Number of Music Playlists?
The Python solution on this page uses O(goal × n) auxiliary space.
- What topics does LeetCode 920. Number of Music Playlists cover?
LeetCode 920. Number of Music Playlists is tagged Math, Dynamic Programming and Combinatorics on LeetCode.