Permutations with Fixed Inversion Count
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given two integers m and n, consider all rearrangements (permutations) of the sequence [1, 2, ..., m], where each integer from 1 through m appears once.
In a 0-indexed arrangement p of length m, an index pair (i, j) counts as an inversion whenever 0 <= i < j < m and p[i] > p[j] — meaning a larger value appears earlier in the list than a smaller value.
Compute how many distinct permutations of [1, 2, ..., m] have precisely n inversions. Because the count can grow very large, return the result modulo 10^9 + 7 (1,000,000,007).
Examples
Example 1
Input: m = 3, n = 2
Output: 2
Out of the 6 permutations of [1, 2, 3], two have 2 inversions: [2, 3, 1] (inverted value pairs (2, 1) and (3, 1)) and [3, 1, 2] (inverted value pairs (3, 1) and (3, 2)).
Example 2
Input: m = 4, n = 2
Output: 5
Among the 24 permutations of [1, 2, 3, 4], five contain 2 inversions: [1, 3, 4, 2], [1, 4, 2, 3], [2, 1, 4, 3], [2, 3, 1, 4], and [3, 1, 2, 4].
Example 3
Input: m = 4, n = 0
Output: 1
Only the ascending sequence [1, 2, 3, 4] has zero out-of-order pairs.
Example 4
Input: m = 3, n = 5
Output: 0
Three elements form only 3 * 2 / 2 = 3 index pairs in total, so even the completely reversed arrangement [3, 2, 1] has only 3 inversions and no permutation can reach 5.
Constraints
1 <= m <= 10000 <= n <= 1000
Step-by-step walkthrough
Understand what an inversion counts
We consider every permutation (rearrangement) of
[1, 2, ..., m]and want to count how many of them contain exactlyninversions, modulo10^9 + 7.An inversion is any pair of positions
(x, y)withx < ywhere a larger number sits to the left of a smaller number (perm[x] > perm[y]). Form = 3, there are3! = 6permutations in total:permutation inverted pairs (left > right) inversion count [1, 2, 3] none 0 [1, 3, 2] (3, 2) 1 [2, 1, 3] (2, 1) 1 [2, 3, 1] (2, 1), (3, 1) 2 [3, 1, 2] (3, 1), (3, 2) 2 [3, 2, 1] (3, 2), (3, 1), (2, 1) 3Two boundary facts immediately stand out:
- Only the sorted array
[1, 2, ..., m]has0inversions. - There are
m * (m - 1) // 2pairs of positions in total, and only the completely reversed array[m, ..., 2, 1]inverts every single pair. Whenevern > m * (m - 1) // 2, no permutation can haveninversions, so the answer is0.
- Only the sorted array
Why brute force hits a factorial wall
A direct approach generates all
m!permutations, checks allm * (m - 1) // 2index pairs in each permutation, and counts how many land onn.That takes
O(m! * m^2)operations. Form = 8,8! = 40,320is fast enough to use as a test oracle. Bym = 15,15!is already over1.3 trillion, and our limit ism = 1000. We need to count permutations in groups rather than building them one by one.Key insight: insert the largest number last
Suppose we already know how many permutations of
[1, 2, ..., size - 1]have each possible inversion count. How can we build every permutation of[1, 2, ..., size]?Take any permutation of
1 .. size - 1and insert the new largest valuesizeinto one of thesizeavailable gaps (from the far right to the far left). Becausesizeis strictly greater than every number already in the list:- The numbers to the left of
sizeare smaller thansize, so they form 0 inversions withsize. - Every number to the right of
sizeis smaller thansize, so every element aftersizeforms an inversion withsize. - Meanwhile, the relative order among
1 .. size - 1never changes, so their old inversions stay intact.
Watch what happens when we insert
size = 4into[2, 1, 3](which already has1inversion,(2, 1)):insertion spot resulting array elements after 4 added inversions new total far right [2, 1, 3, 4] 0 +0 1 + 0 = 1 1 step from right [2, 1, 4, 3] 1 (3) +1 1 + 1 = 2 2 steps from right [2, 4, 1, 3] 2 (1, 3) +2 1 + 2 = 3 far left [4, 2, 1, 3] 3 (2, 1, 3) +3 1 + 3 = 4Every permutation of
1 .. sizecomes from a unique permutation of1 .. size - 1(just erasesizeto see which one) and a unique insertion spot addingkinversions for some0 <= k <= size - 1.So if
ways[inv]is the number of permutations of1 .. size - 1withinvinversions, then after insertingsize, the new countnew_ways[inv]is the sum of up tosizeentries:new_ways[inv] = ways[inv] + ways[inv - 1] + ... + ways[inv - (size - 1)](Any term with a negative index is treated as
0, and we never need indices abovenbecause inserting elements never removes inversions.)- The numbers to the left of
Speed up each row with a sliding window
If we recomputed that sum from scratch for every
(size, inv)cell, each cell would add up tomin(size, inv + 1)numbers. Atm = 1000, n = 1000, that is roughly3.3 * 10^8additions — too slow in Python.Look at two adjacent sums for
size = 4:inv = 3: ways[0] + ways[1] + ways[2] + ways[3] inv = 4: ways[1] + ways[2] + ways[3] + ways[4] ^^^^^^^^ ^^^^^^^ leaves (index 4 - 4 = 0) enters (index 4)Moving from
inv - 1toinvshifts a window of widthsizeone step to the right:ways[inv]enters on the right:window_sum += ways[inv].- Once
inv >= size, the elementways[inv - size]issizesteps behindinv(which would correspond to addingsizeinversions, one more than the maximumsize - 1), so we drop it:window_sum -= ways[inv - size].
Now every cell takes
O(1)work, and a whole row takesO(n).for size in range(2, m + 1): new_ways = [0] * (n + 1) window_sum = 0 for inv in range(n + 1): window_sum += ways[inv] if inv >= size: window_sum -= ways[inv - size] new_ways[inv] = window_sum % MOD ways = new_waysNote that each
ways[...]is in[0, MOD - 1], and every value subtracted fromwindow_sumwas added towindow_sumexactlysizesteps earlier. Thuswindow_sumstays non-negative and represents the exact sum of the active window; reducing moduloMODwhen writingnew_ways[inv]keeps all stored counts small.Trace m = 4, n = 2 row by row
We start at
size = 1withways = [1, 0, 0](only[1], which has0inversions) and advance up tosize = 4:size = 1 (base): ways = [1, 0, 0] size = 2 (width 2): inv=0: ways[0] = 1 inv=1: ways[0]+ways[1] = 1 inv=2: ways[1]+ways[2] = 0 -> ways = [1, 1, 0] size = 3 (width 3): inv=0: ways[0] = 1 inv=1: ways[0]+ways[1] = 2 inv=2: ways[0]+ways[1]+ways[2] = 2 -> ways = [1, 2, 2] size = 4 (width 4): inv=0: 1 = 1 inv=1: 1 + 2 = 3 inv=2: 1 + 2 + 2 = 5 -> ways = [1, 3, 5]At the end,
ways[2] = 5andways[0] = 1, matching Examples 2 and 3 (m = 4, n = 2 -> 5andm = 4, n = 0 -> 1). Notice that aftersize = 3,ways[2] = 2, which also matches Example 1 (m = 3, n = 2 -> 2)!Complete solution
Putting the impossibility check, the base row
ways = [1, 0, ...], and the sliding-window row transitions together gives the complete solution:from typing import Any, Dict, List, Optional, Set, Tuple MOD = 10**9 + 7 def count_permutations_with_inversions(m: int, n: int) -> int: # A permutation of m numbers has m * (m - 1) // 2 pairs total, # so even the fully reversed array cannot exceed max_inversions. max_inversions = m * (m - 1) // 2 if n > max_inversions: return 0 # ways[inv]: count of permutations of [1..size] with exactly inv inversions. # Base case size = 1: [1] is the only permutation and has 0 inversions. ways = [0] * (n + 1) ways[0] = 1 # Grow permutations from [1..size-1] to [1..size] by inserting `size`. for size in range(2, m + 1): new_ways = [0] * (n + 1) # window_sum tracks ways[max(0, inv - size + 1)] + ... + ways[inv], # covering the `size` insertion spots that add 0..size-1 new inversions. window_sum = 0 for inv in range(n + 1): window_sum += ways[inv] # Inserting `size` can add at most `size - 1` inversions; once # inv >= size, ways[inv - size] would require `size` new inversions, # so drop it from the left edge of the sliding window. if inv >= size: window_sum -= ways[inv - size] new_ways[inv] = window_sum % MOD ways = new_ways return ways[n]✅ Submit now — all tests should pass.
Intuition & how it works
Imagine lining up m people of heights 1 through m, introducing them one by one from shortest to tallest. An inversion is a pair of people where someone taller stands ahead of someone shorter. Because each newcomer is taller than everyone already standing in line, inserting person size with k people to their right creates exactly k brand-new inversions (0 <= k <= size - 1), and it does not disturb any inversions among the shorter people already placed. That lets us use dynamic programming (solving a big counting problem by building a table of counts for smaller sizes step by step) alongside a sliding window (a running sum over a fixed-width slice of an array updated by adding the incoming item and subtracting the outgoing item).
The naive approach generates every permutation (every possible ordering of 1..m) and checks all pairs of indices, taking O(m! * m^2) work. Since m! already exceeds 3.6 million at m = 10, listing permutations one by one is completely impossible for m = 1000. Even a straightforward DP that re-adds up to size previous terms from scratch for every cell would perform roughly 3.3 * 10^8 additions at m = n = 1000, whereas a sliding window updates each cell in a single addition and subtraction.
Walk through m = 3, n = 2 (ways[0..2] tracks counts for 0, 1, and 2 inversions):
- Start at
size = 1:[1]has0inversions, soways = [1, 0, 0]. - Insert
size = 2(window width2, adding0or1inversions):new_ways[0] = 1([1, 2]),new_ways[1] = 1 + 0 = 1([2, 1]), andnew_ways[2] = 0 + 0 = 0, givingways = [1, 1, 0]. - Insert
size = 3(window width3, adding0,1, or2inversions):new_ways[0] = 1,new_ways[1] = 1 + 1 = 2, andnew_ways[2] = 1 + 1 + 0 = 2([2, 3, 1]and[3, 1, 2]), returningways[2] = 2.
Complexity
- Time:
O(m * n). The outer loop runsm - 1times (size = 2 .. m), and the inner loop scansn + 1inversion counts (inv = 0 .. n), doingO(1)additions, subtractions, and a remainder operation at each step. At the maximumm = 1000, n = 1000, that is about10^6simple iterations. - Space:
O(n). Because rowsizeonly reads from rowsize - 1, we only store two arrays (waysandnew_ways) of lengthn + 1rather than a fullm * (n + 1)table.
Edge cases
m = 1:[1]is the sole permutation. Ifn = 0,ways[0]immediately returns1; ifn > 0,n > max_inversions(0) immediately returns0.n = 0: Only the sorted array[1, 2, ..., m]has zero inversions, so the answer is1for everym >= 1.n = m * (m - 1) // 2: Only the reversed array[m, ..., 2, 1]achieves the maximum possible inversions, returning1.n > m * (m - 1) // 2: Impossible (for instancem = 3, n = 5orm = 45, n = 991), caught upfront and returning0.- Huge exact counts: Even for
m = 20, n = 95, the true count exceeds6.2 * 10^16, so modular arithmetic (taking remainders modulo10^9 + 7at every row) is essential to keep numbers compact and fast.
Common mistakes
- Off-by-one window width (
inv >= size - 1instead ofinv >= size). Insertingsizeintosize - 1elements offerssizeslots, adding0, 1, ..., size - 1inversions (sizeterms total). Subtracting atinv >= size - 1makes the window one element too narrow and undercounts. - Summing the window with an inner loop. Writing
sum(ways[max(0, inv - size + 1) : inv + 1])turnsO(m * n)intoO(m * n * min(m, n)), timing out onm = n = 1000. - Negative remainders in C++ or Java. If you reduce
window_summoduloMODon every step in languages where%can return a negative remainder,(window_sum - ways[inv - size]) % MODcan go negative unless you addMODfirst. Keepingwindow_sumas the exact sum of the active window avoids negative values altogether becausewindow_sumnever exceedssize * MOD(~10^12, well inside 64-bit integers). - Choosing which number goes last without re-ranking. Trying to track the exact subset of unused numbers explodes into
2^mstates. Inserting values in increasing order1, 2, ..., mavoids tracking subsets because the newest number is always larger than all previously placed numbers.
Alternative approaches
- Prefix sums per row: Compute a prefix sum array (where
prefix[k]storesways[0] + ... + ways[k]) at the start of each row, then read each range sumways[left .. inv]inO(1)via subtraction. This has the exact sameO(m * n)time andO(n)space as the sliding window. - Polynomial multiplication (generating functions): Inserting
sizemultiplies the counting polynomial by(1 + x + x^2 + ... + x^(size - 1)), where the exponent ofxtracks the inversion count. Truncating atx^nat each step produces the exact same recurrence as our DP.
Follow-up questions
- How can you compute the inversion count of a single permutation of length up to 10^5? Checking all pairs takes
O(m^2), which is too slow for10^5. Instead, use merge sort: whenever an element from the right half is placed beforerremaining elements of the already-sorted left half, allrof those left elements are larger and sit earlier, so addrto the total inO(m log m)time. You can also scan left to right with a Fenwick tree (an array-based tree structure supporting prefix sums and point updates inO(log m)time) to count how many larger elements appeared earlier. - How would you build one explicit permutation of 1 through m that has a requested count of n inversions? First check
0 <= n <= m * (m - 1) // 2. Greedily decide forsize = mdown to1how many smaller elements will sit aftersize: setc[size] = min(size - 1, remaining_n)and subtractc[size]fromremaining_n. Inserting1..min order so thatsizehasc[size]elements after it builds a valid permutation inO(m^2)time with a plain list (orO(m log m)with an order-statistic tree). - If up to 10^5 independent (m, n) queries arrive with m, n <= 1000, how would you answer each query in constant time? Instead of discarding previous rows, keep all
1001rows in a 2D tabledp[size][inv]of size1001 * 1001. Precomputing the entire table once takesO(M * N)(~10^6operations), after which every(m, n)query is answered inO(1)time by looking updp[m][n](or returning0whenn > m * (m - 1) // 2).
Follow-up questions
- How can you compute the inversion count of a single permutation of length up to 10^5?
- How would you build one explicit permutation of 1 through m that has a requested count of n inversions?
- If up to 10^5 independent (m, n) queries arrive with m, n <= 1000, how would you answer each query in constant time?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array