The Count the Number of Inversions interview question typically asks you to find the total number of inversions in an array. An inversion is a pair of indices such that and . This is a standard measure of how "unsorted" an array is.
However, in some advanced variations, you are given a set of requirements (e.g., at index , there must be exactly inversions in the prefix ) and asked to find how many permutations of satisfy these conditions.
Companies like Google and Salesforce use this to test a candidate's knowledge of dynamic programming and combinatorics. It requires a deep understanding of how the number of inversions changes when a new element is inserted into a permutation. If you insert the -th element into a permutation of elements, you can create anywhere from 0 to new inversions, depending on its position.
This problem is solved using Dynamic Programming.
dp[i][j] is the number of permutations of length i with exactly j inversions.dp[i][j] = sum(dp[i-1][j-k]) for .dp[i][k] is kept, and all other dp[i][j] are set to 0., requirements: index 2 must have 2 inversions.
dp[1][0] = 1.dp[2][0]=1, dp[2][1]=1 (sum of dp[1] over range of 2).dp[3][j]: sum of dp[2] over range of 3.
dp[3][2] = dp[2][2] + dp[2][1] + dp[2][0] = 0 + 1 + 1 = 2.
Result = 2. (Permutations: [2, 0, 1] and [1, 2, 0]).(a - b + mod) % mod).dp[1][0] = 1.Master the "Insertion Method" for permutations. Understanding how the -th element's position affects global properties (like inversions or peaks) is the key to solving many Hard-level combinatorics DP problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Profitable Schemes | Hard | Solve | |
| Minimum Swaps To Make Sequences Increasing | Hard | Solve | |
| Coin Path | Hard | Solve | |
| Count Number of Special Subsequences | Hard | Solve | |
| Form Largest Integer With Digits That Add up to Target | Hard | Solve |