#629

K Inverse Pairs Array

Hard
Dynamic Programming
LeetCode ↗

Approaches

💡

Intuition

Time Space

The brute force approach generates all possible permutations of the array and counts the number of inverse pairs in each permutation. This is straightforward but inefficient for larger values of n.

⚙️

Algorithm

3 steps
  1. 1Step 1: Generate all permutations of the array containing numbers from 1 to n.
  2. 2Step 2: For each permutation, count the number of inverse pairs.
  3. 3Step 3: Return the count of permutations that have exactly k inverse pairs.
solution.py17 lines
1# Full working Python code
2from itertools import permutations
3
4def countInversePairs(n, k):
5    def count_pairs(arr):
6        count = 0
7        for i in range(len(arr)):
8            for j in range(i + 1, len(arr)):
9                if arr[i] > arr[j]:
10                    count += 1
11        return count
12
13    count = 0
14    for perm in permutations(range(1, n + 1)):
15        if count_pairs(perm) == k:
16            count += 1
17    return count % (10**9 + 7)

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.