Number of Music Playlists — LeetCode 920 Python Solution

HardMathDynamic ProgrammingCombinatorics
Problem
#920
Reading time
2 min

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

MeasureComplexity
TimeO(goal \times n)
SpaceO(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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview