Skip to content
StackDecode
Divide & conquerAnimated

Count Inversions

Count while merge sorting: items jumping over larger ones.

Time

O(n log n)

Extra space

O(n)

Use it for

How far a list is from sorted.

How it works

  1. An inversion is a pair of positions i < j with a[i] > a[j]: two items that are in the wrong order.
  2. Counting all pairs one by one takes O(n²). Instead, run merge sort.
  3. While merging two sorted halves, whenever you take an element from the right half, it is smaller than every element still waiting in the left half. Each of those is an inversion, so add that many at once.
  4. Splits plus merges: O(n log n).

Watch it run

Loading animation…