Number of Music Playlists — LeetCode 920 Python Solution
HardMathDynamic ProgrammingCombinatorics
- Problem
- #920
- Pattern
- Dynamic Programming
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(goal \times n) |
| Space | O(goal \times n) auxiliary |
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
LeetCode 62Unique PathsMediumLeetCode 458Poor PigsHardLeetCode 1359Count All Valid Pickup and Delivery OptionsHardLeetCode 1467Probability of a Two Boxes Having The Same Number of Distinct BallsHardLeetCode 1569Number of Ways to Reorder Array to Get Same BSTHardLeetCode 1621Number of Sets of K Non-Overlapping Line SegmentsMedium
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 \times n).
- What is the space complexity of LeetCode 920. Number of Music Playlists?
- The Python solution on this page uses O(goal \times 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.