KatInterview

Theoretical Mean and Variance of Permutation Inversions

Math & Bit ManipulationAuto-graded · 22 test cases
EasyAuto-gradedMath & Bit Manipulationmathcombinatoricsstatistics

Last 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).