Theoretical Mean and Variance of Permutation Inversions
Math & Bit ManipulationAuto-graded · 22 test casesLast updated
Derive and evaluate the closed-form expected value and variance for the number of inversions in a uniformly random permutation.
A permutation of the set ${1, 2, \dots, n}$ is chosen uniformly at random. An inversion is defined as a pair of indices $(i, j)$ such that $1 \le i < j \le n$ and $P[i] > P[j]$.
Given an integer $n$, compute the exact theoretical expected value (mean) and variance of the total number of inversions across all uniformly distributed random permutations of size $n$.
Return the results as a tuple of floats (mean, variance).
Constraints
- $1 \le n \le 1000$
Examples
Example 1
Input: inversion_stats(1)
Output: [0, 0]
Example 2
Input: inversion_stats(2)
Output: [0.5, 0.25]
Example 3
Input: inversion_stats(3)
Output: [1.5, 0.9166666666666666]
Example 4
Input: inversion_stats(10)
Output: [22.5, 31.25]
Hints
Hint 1
Use indicator variables for each pair of indices (i, j) with i < j.
Hint 2
Recall that linearity of expectation applies even when variables are dependent.
Hint 3
Consider using independence by building the permutation element by element (e.g., using Lehmer code properties).
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To compute the expected value and variance of the number of inversions $I$ in a random permutation of length $n$:
-
Expected Value: Let $X_{ij}$ be an indicator variable equal to $1$ if $P[i] > P[j]$ (where $i < j$) and $0$ otherwise. For any fixed pair $(i, j)$, symmetry implies that $P[i] > P[j]$ half of the time, so $E[X_{ij}] = 1/2$. By linearity of expectation: $$E[I] = \sum_{1 \le i < j \le n} E[X_{ij}] = \binom{n}{2} \cdot \frac{1}{2} = \frac{n(n-1)}{4}$$
-
Variance via Lehmer Code: Instead of computing covariances among dependent indicators, consider inserting elements $k = 1, \dots, n$ sequentially. When the $k$-th element is inserted, it forms $Y_k$ inversions with already placed elements, where $Y_k$ is uniformly distributed over ${0, 1, \dots, k-1}$. Importantly, $Y_1, Y_2, \dots, Y_n$ are independent variables.
The variance of a discrete uniform random variable on ${0, \dots, k-1}$ is $\frac{k^2 - 1}{12}$. Summing over all independent $Y_k$: $$\mathrm{Var}(I) = \sum_{k=1}^n \mathrm{Var}(Y_k) = \sum_{k=1}^n \frac{k^2 - 1}{12} = \frac{n(n-1)(2n+5)}{72}$$
Complexity
- Time Complexity: $\mathcal{O}(1)$ since the result is computed directly using constant arithmetic operations.
- Space Complexity: $\mathcal{O}(1)$ auxiliary memory.
from typing import Tuple
def inversion_stats(n: int) -> Tuple[float, float]:
mean = n * (n - 1) / 4.0
variance = n * (n - 1) * (2 * n + 5) / 72.0
return (mean, variance)