Arrays & Hashing · Pattern 8 of 26

Merge sort, and counting while you merge

Merge sort splits, sorts both halves, then merges. During the merge you know which left values are bigger than a right value, which counts inversions and similar pairs in O(n log n).

2 variations · 4 problems · 2 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Count pairs i < j with a[i] > a[j] (or a[i] > 2·a[j])
  • Sort with guaranteed O(n log n)
  • Rearrange stably, keeping relative order

The template

Merge Sort Like Approach
long countInversions(int[] a) {
    return sort(a, new int[a.length], 0, a.length - 1);
}
long sort(int[] a, int[] tmp, int lo, int hi) {
    if (lo >= hi) return 0;
    int mid = (lo + hi) / 2;
    long count = sort(a, tmp, lo, mid) + sort(a, tmp, mid + 1, hi);
    int i = lo, j = mid + 1, k = lo;
    while (i <= mid && j <= hi) {
        if (a[i] <= a[j]) tmp[k++] = a[i++];
        else { count += mid - i + 1; tmp[k++] = a[j++]; }   // a[i..mid] are all > a[j]
    }
    while (i <= mid) tmp[k++] = a[i++];
    while (j <= hi) tmp[k++] = a[j++];
    for (k = lo; k <= hi; k++) a[k] = tmp[k];
    return count;
}

The variations

  1. 1Count pairs while merging

    When a right value is taken before left values, every remaining left value forms a pair with it. For a[i] > 2·a[j], count with a second pointer before the merge.

    Now you solve
  2. 2Merge sort itself, and stable rearranging

    Split, sort halves, merge. Merging keeps equal elements in order, which is how you move negatives before positives without changing their relative order.

    Worked example Sort an Array Medium Read the solution
    Now you solve

Mistakes to avoid

  • Counting with < instead of <=: equal values are not inversions.
  • Using int for the count: n = 10⁵ gives up to 5·10⁹ inversions.
  • For reverse pairs (a[i] > 2·a[j]), counting inside the merge loop instead of in a separate pass before merging.
Next: Dutch national flag: three-way partition →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.