#3193
Count the Number of Inversions
HardArrayDynamic ProgrammingDynamic ProgrammingCombinatorial Counting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n * k) |
| Space | O(n) | O(n * k) |
💡
Intuition
Time O(n * k)Space O(n * k)
Instead of generating permutations, we use dynamic programming to count valid permutations directly based on the inversion requirements. This is efficient and avoids the combinatorial explosion of the brute-force approach.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a DP table where dp[i][j] represents the number of ways to arrange i elements with j inversions.
- 2Step 2: Fill the DP table using the relation: dp[i][j] = dp[i-1][j] + dp[i-1][j-1] + ... + dp[i-1][0].
- 3Step 3: For each requirement, sum the valid configurations from the DP table that match the inversion count.
solution.py15 lines
1def count_valid_permutations(n, requirements):
2 MOD = 10**9 + 7
3 dp = [[0] * (400 + 1) for _ in range(n + 1)]
4 dp[0][0] = 1
5 for i in range(1, n + 1):
6 for j in range(400 + 1):
7 dp[i][j] = dp[i - 1][j]
8 if j > 0:
9 dp[i][j] = (dp[i][j] + dp[i][j - 1]) % MOD
10 if j >= i:
11 dp[i][j] = (dp[i][j] - dp[i - 1][j - i]) % MOD
12 result = 1
13 for end, cnt in requirements:
14 result = (result * dp[end + 1][cnt]) % MOD
15 return resultℹ
Complexity note: This complexity arises from filling the DP table where n is the number of elements and k is the maximum number of inversions (400 in this case).
- 1Dynamic programming can significantly reduce the time complexity for counting permutations with specific properties.
- 2Understanding how to build and use a DP table is crucial for solving combinatorial problems efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.