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 <= 1000
  • 0 <= n <= 1000

Step-by-step walkthrough

  1. Understand what an inversion counts

    We consider every permutation (rearrangement) of [1, 2, ..., m] and want to count how many of them contain exactly n inversions, modulo 10^9 + 7.

    An inversion is any pair of positions (x, y) with x < y where a larger number sits to the left of a smaller number (perm[x] > perm[y]). For m = 3, there are 3! = 6 permutations 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)              3
    

    Two boundary facts immediately stand out:

    • Only the sorted array [1, 2, ..., m] has 0 inversions.
    • There are m * (m - 1) // 2 pairs of positions in total, and only the completely reversed array [m, ..., 2, 1] inverts every single pair. Whenever n > m * (m - 1) // 2, no permutation can have n inversions, so the answer is 0.
  2. Why brute force hits a factorial wall

    A direct approach generates all m! permutations, checks all m * (m - 1) // 2 index pairs in each permutation, and counts how many land on n.

    That takes O(m! * m^2) operations. For m = 8, 8! = 40,320 is fast enough to use as a test oracle. By m = 15, 15! is already over 1.3 trillion, and our limit is m = 1000. We need to count permutations in groups rather than building them one by one.

  3. 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 - 1 and insert the new largest value size into one of the size available gaps (from the far right to the far left). Because size is strictly greater than every number already in the list:

    • The numbers to the left of size are smaller than size, so they form 0 inversions with size.
    • Every number to the right of size is smaller than size, so every element after size forms an inversion with size.
    • Meanwhile, the relative order among 1 .. size - 1 never changes, so their old inversions stay intact.

    Watch what happens when we insert size = 4 into [2, 1, 3] (which already has 1 inversion, (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 = 4
    

    Every permutation of 1 .. size comes from a unique permutation of 1 .. size - 1 (just erase size to see which one) and a unique insertion spot adding k inversions for some 0 <= k <= size - 1.

    So if ways[inv] is the number of permutations of 1 .. size - 1 with inv inversions, then after inserting size, the new count new_ways[inv] is the sum of up to size entries:

    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 above n because inserting elements never removes inversions.)

  4. 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 to min(size, inv + 1) numbers. At m = 1000, n = 1000, that is roughly 3.3 * 10^8 additions — 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 - 1 to inv shifts a window of width size one step to the right:

    1. ways[inv] enters on the right: window_sum += ways[inv].
    2. Once inv >= size, the element ways[inv - size] is size steps behind inv (which would correspond to adding size inversions, one more than the maximum size - 1), so we drop it: window_sum -= ways[inv - size].

    Now every cell takes O(1) work, and a whole row takes O(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_ways
    

    Note that each ways[...] is in [0, MOD - 1], and every value subtracted from window_sum was added to window_sum exactly size steps earlier. Thus window_sum stays non-negative and represents the exact sum of the active window; reducing modulo MOD when writing new_ways[inv] keeps all stored counts small.

  5. Trace m = 4, n = 2 row by row

    We start at size = 1 with ways = [1, 0, 0] (only [1], which has 0 inversions) and advance up to size = 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] = 5 and ways[0] = 1, matching Examples 2 and 3 (m = 4, n = 2 -> 5 and m = 4, n = 0 -> 1). Notice that after size = 3, ways[2] = 2, which also matches Example 1 (m = 3, n = 2 -> 2)!

  6. 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] has 0 inversions, so ways = [1, 0, 0].
  • Insert size = 2 (window width 2, adding 0 or 1 inversions): new_ways[0] = 1 ([1, 2]), new_ways[1] = 1 + 0 = 1 ([2, 1]), and new_ways[2] = 0 + 0 = 0, giving ways = [1, 1, 0].
  • Insert size = 3 (window width 3, adding 0, 1, or 2 inversions): new_ways[0] = 1, new_ways[1] = 1 + 1 = 2, and new_ways[2] = 1 + 1 + 0 = 2 ([2, 3, 1] and [3, 1, 2]), returning ways[2] = 2.

Complexity

  • Time: O(m * n). The outer loop runs m - 1 times (size = 2 .. m), and the inner loop scans n + 1 inversion counts (inv = 0 .. n), doing O(1) additions, subtractions, and a remainder operation at each step. At the maximum m = 1000, n = 1000, that is about 10^6 simple iterations.
  • Space: O(n). Because row size only reads from row size - 1, we only store two arrays (ways and new_ways) of length n + 1 rather than a full m * (n + 1) table.

Edge cases

  • m = 1: [1] is the sole permutation. If n = 0, ways[0] immediately returns 1; if n > 0, n > max_inversions (0) immediately returns 0.
  • n = 0: Only the sorted array [1, 2, ..., m] has zero inversions, so the answer is 1 for every m >= 1.
  • n = m * (m - 1) // 2: Only the reversed array [m, ..., 2, 1] achieves the maximum possible inversions, returning 1.
  • n > m * (m - 1) // 2: Impossible (for instance m = 3, n = 5 or m = 45, n = 991), caught upfront and returning 0.
  • Huge exact counts: Even for m = 20, n = 95, the true count exceeds 6.2 * 10^16, so modular arithmetic (taking remainders modulo 10^9 + 7 at every row) is essential to keep numbers compact and fast.

Common mistakes

  • Off-by-one window width (inv >= size - 1 instead of inv >= size). Inserting size into size - 1 elements offers size slots, adding 0, 1, ..., size - 1 inversions (size terms total). Subtracting at inv >= size - 1 makes 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]) turns O(m * n) into O(m * n * min(m, n)), timing out on m = n = 1000.
  • Negative remainders in C++ or Java. If you reduce window_sum modulo MOD on every step in languages where % can return a negative remainder, (window_sum - ways[inv - size]) % MOD can go negative unless you add MOD first. Keeping window_sum as the exact sum of the active window avoids negative values altogether because window_sum never exceeds size * 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^m states. Inserting values in increasing order 1, 2, ..., m avoids 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] stores ways[0] + ... + ways[k]) at the start of each row, then read each range sum ways[left .. inv] in O(1) via subtraction. This has the exact same O(m * n) time and O(n) space as the sliding window.
  • Polynomial multiplication (generating functions): Inserting size multiplies the counting polynomial by (1 + x + x^2 + ... + x^(size - 1)), where the exponent of x tracks the inversion count. Truncating at x^n at 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 for 10^5. Instead, use merge sort: whenever an element from the right half is placed before r remaining elements of the already-sorted left half, all r of those left elements are larger and sit earlier, so add r to the total in O(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 in O(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 for size = m down to 1 how many smaller elements will sit after size: set c[size] = min(size - 1, remaining_n) and subtract c[size] from remaining_n. Inserting 1..m in order so that size has c[size] elements after it builds a valid permutation in O(m^2) time with a plain list (or O(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 1001 rows in a 2D table dp[size][inv] of size 1001 * 1001. Precomputing the entire table once takes O(M * N) (~10^6 operations), after which every (m, n) query is answered in O(1) time by looking up dp[m][n] (or returning 0 when n > m * (m - 1) // 2).

Follow-up questions

Similar questions

More Turing interview questions

All 1 Turing questions →