K Inverse Pairs Array — LeetCode 629 Python Solution

HardDynamic Programming
Problem
#629
Reading time
2 min

The problem

For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j]. Given two integers n and k, return the number of different arrays consisting of numbers from 1 to n such that there are exactly k inverse pairs.

Example

Input
n = 3, k = 0
Output
1
Explanation
Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.

Python solution

Python
class Solution:
    def kInversePairs(self, n: int, k: int) -> int:
        mod = 10**9 + 7
        f = [1] + [0] * k
        s = [0] * (k + 2)
        for i in range(1, n + 1):
            for j in range(1, k + 1):
                f[j] = (s[j + 1] - s[max(0, j - (i - 1))]) % mod
            for j in range(1, k + 2):
                s[j] = (s[j - 1] + f[j - 1]) % mod
        return f[k]

Complexity

MeasureComplexity
TimeO(n \times k)
SpaceO(k) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 629. K Inverse Pairs Array 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 629. K Inverse Pairs Array?
LeetCode 629. K Inverse Pairs Array is rated Hard on LeetCode.
What is the time complexity of LeetCode 629. K Inverse Pairs Array?
The Python solution on this page runs in O(n \times k).
What is the space complexity of LeetCode 629. K Inverse Pairs Array?
The Python solution on this page uses O(k) auxiliary space.
What topics does LeetCode 629. K Inverse Pairs Array cover?
LeetCode 629. K Inverse Pairs Array is tagged Dynamic Programming 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