Scrivio Interview library
Sorting and intervalsSorting and searchingReported 15 times · 15 min read · updated 15 November 2026

Count the inversions in an array of integers.

1What an inversion is, told as children lining up for a photograph

Imagine a teacher lining up children for a school photograph. They should stand from the shortest on the left to the tallest on the right. The line has formed in a hurry, though, and the teacher wants to know how badly mixed it is. One fair measure is to count every pair of children where the taller one stands somewhere to the left of the shorter one. Each such pair is one small complaint, and a perfect line has none.

The question calls such a pair an inversion. We are given an array of integers, the heights, and an inversion is a pair of positions i and j with i before j, so i < j, where the earlier value is bigger, a[i] > a[j]. The two children need not stand next to each other; any pair counts. We must return how many inversions the array has.

Let us keep one example for the whole article, [2, 4, 1, 3, 5], and count by hand. We take each child in turn and look only to its right. The 2 has one shorter child to its right, the 1. The 4 has two, the 1 and the 3. The 1, the 3 and the 5 have none. So there are 1 + 2 = 3 inversions, the pairs (2, 1), (4, 1) and (4, 3).

Two extremes help to feel the size of the number. A sorted array has no inversions at all. A reversed array, such as [4, 3, 2, 1], has every pair out of order, which for 4 values is 6 pairs and for n values is n(n - 1)/2. The counting looks as if it must look at every pair, but the problem is smaller than it looks, as we shall see.

PictureThe example line and its three inversions

Five children by height. The marked cells take part in at least one inversion.

  1. 2041123354
    inversions
    (2,1) (4,1) (4,3)
    answer
    3

    1In [2, 4, 1, 3, 5] three pairs are out of order: 2 before 1, 4 before 1, and 4 before 3. So the answer is 3.

What to assume

Can values repeat, and does an equal pair count?
We assume repeats are allowed and do not count, because the definition says strictly bigger.
May we change the array?
We assume not.
And how big can it be?
Perhaps a hundred thousand values. Then the answer can reach about five billion, more than an int can hold, so we return a long.

A careful candidate asks a few questions first. Can values repeat, and does an equal pair count? We assume repeats are allowed and do not count, because the definition says strictly bigger. May we change the array? We assume not, so we will work on a copy. And how big can it be? Perhaps a hundred thousand values. Then the answer can reach about five billion, more than an int can hold, so we return a long.

2How to recognise a merge sort counting problem

A beginner reading this question naturally writes two loops, one choosing the earlier position and one choosing the later, and counts the pairs that are out of order. That is the right first step, and we will write it. But with a hundred thousand values it makes about five billion comparisons, so the question is really asking for something faster.

So let us look for clues, one at a time. The first clue is the phrase out of order. What we count is about order, which values come before which, and the family of algorithms that deals with order is sorting. Every sorting method removes inversions as it works, so it is natural to ask whether one of them could count them on the way.

The second clue is that a pair may be far apart. Two values at opposite ends of the array still form an inversion. Methods that only compare neighbours, or that slide a small window along, cannot see such pairs cheaply. We need a method that compares values from distant parts of the array in bulk.

Those clues point to the sorting and intervals pattern, and within it to merge sort. Merge sort works by splitting. It cuts the array into a left half and a right half, sorts each half the same way, and then merges the two sorted halves into one sorted array, the way you would merge two sorted piles of exam papers by always taking the smaller top paper. During that merge, values from the left half meet values from the right half, which is exactly where distant pairs meet.

The rule to carry to new problems is this. When a question counts pairs i < j that break an order condition, such as a[i] > a[j], or a[i] more than twice a[j], think of a merge sort that counts across the two halves while it merges. That usually costs O(n log n), read as order n log n, instead of O(n squared).

Two other tools look possible. A Fenwick tree, also called a binary indexed tree, can count, for each value, how many bigger values came before it, also in O(n log n), but it is more machinery to explain in an interview. A hash map or two pointers do not fit, because the condition mixes positions and values, and neither tool keeps both in view at once.

3The honest first attempt, a brute force over every pair

The honest first attempt, the brute force, follows the definition exactly, just as we counted by hand. For every position i we look at every later position j, and we add one whenever a[i] > a[j]. It is clearly correct, and having it in hand gives us something to test a faster version against.

Java
// Brute force: check every pair i < j.
static long countInversions(int[] a) {
long count = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] > a[j]) count++; // an earlier value is bigger: one inversion
}
}
return count;
}

Let us count its work on the example. The 2 is compared with four values to its right, the 4 with three, the 1 with two and the 3 with one, so 4 + 3 + 2 + 1 = 10 comparisons find our 3 inversions. For n values that is n(n - 1)/2 comparisons, about half of n times n, which we write as O(n squared); doubling the array makes the work about four times larger. For a hundred thousand values it is about five billion comparisons. The extra memory, called the space, is O(1), a single counter.

So where is the waste? Let us return to the photograph and split the line in the middle, into a left group 2, 4, 1 and a right group 3, 5. Every complaint is one of three kinds. Both children are in the left group, both are in the right group, or one is on each side, which we will call a cross pair. Now ask a question about the cross pairs. Does it matter in what order the left group stands among themselves? It does not. The pair (4, 3) is a complaint because 4 is somewhere on the left and 3 somewhere on the right, whatever their exact places. The brute force checks those cross pairs one comparison at a time, although their answer does not depend on the order inside each group.

4From the waste to counting while we merge

That observation lets us do something that looks dangerous at first. We may sort each half before counting the cross pairs. A beginner usually objects here. If we sort the left half, have we not destroyed the very disorder we were trying to count? Let us look at the picture before answering.

Step throughSorting inside a half keeps every cross pair

The left half is indexes 0 to 2 and the right half is indexes 3 and 4. Watch the pair (4, 3) across the middle.

  1. 2041123354mid
    left half
    2 4 1
    right half
    3 5
    inside left
    (2,1) (4,1)
    cross pairs
    (4,3)

    1Split [2, 4, 1, 3, 5] into a left half 2, 4, 1 and a right half 3, 5. Only one pair crosses the middle out of order, 4 on the left and 3 on the right.

  2. 1021423354mid
    left half
    1 2 4
    right half
    3 5
    inside left
    counted, now sorted
    cross pairs
    (4,3)

    2After the left half is sorted into 1, 2, 4, the two inversions inside it are gone, but 4 is still on the left and 3 still on the right, so the cross pair is unchanged.

Sorting the left half did remove two inversions, (2, 1) and (4, 1), but those were inside the half, and the recursive call that sorted the half counts them first and returns that number. The cross pair survived untouched, because sorting only moves values within their own half. So nothing is lost, as long as each recursive call counts its own inversions while it sorts.

Why do we want the halves sorted? Because then the cross pairs can be counted in bulk during the merge. The merge keeps a front pointer i into the sorted left half and a front pointer j into the sorted right half, and each step writes the smaller of the two front values. Suppose the right front value is smaller than the left front value. The left half is sorted, so every left value still waiting, from i up to mid, is at least as big as the left front, and so bigger than our right value. And every one of them came from earlier in the original array, because the whole left half lies before the whole right half. So each waiting left value forms one inversion with it, and there are mid - i + 1 of them, which we add in a single step.

When the left front value is smaller or equal, we write it and add nothing. Every right value still waiting is at least as big as it, so it forms no cross inversion with any of them. This is where ties are decided. If the two front values are equal, we take the left one first, so an equal pair is never counted, which matches the definition.

Why mid - i + 1 and not just 1? This is the mistake beginners make most often. Adding 1 counts only the left front value, but all the waiting values behind it are bigger still. The plus one is there because both i and mid are counted; from index 0 to index 1 there are two values, not one.

So the whole method reads like this. Count the inversions inside the left half and sort it, count those inside the right half and sort it, then merge the halves while adding mid - i + 1 each time a right value goes first. The three groups add up to every inversion, and the merge is still a single pass over the values, so the counting costs nothing extra beyond merge sort itself.

5Watching the count grow as the merges run

The picture follows the final program on [2, 4, 1, 3, 5] in the order the recursion runs its merges. There are four merges. The first three are small, and the last one joins [1, 2, 4] with [3, 5].

In each frame, the cells show the values the current merge is reading, and values outside it are dimmed. The panel shows the two pieces being merged, the values written so far, what this step added to the count, and the running count.

Step throughCounting inversions while merge sort sorts [2, 4, 1, 3, 5]

The cells show the numbers the current merge reads. Cells outside the merge are dimmed, values already written are done, and i and j are the fronts of the two halves.

  1. 2041123354
    merging
    -
    written
    -
    added
    -
    count
    0

    1The recursion splits the array at mid = 2 into 2, 4, 1 and 3, 5, then splits again until every piece is one number. A single number has no inversions.

  2. 2041123354
    merging
    [2] and [4]
    written
    2 4
    added
    0
    count
    0

    2The first merge joins [2] and [4]. 2 is not bigger than 4, so we write 2 and then 4, and nothing is added. The pair is already in order.

  3. 2041123354ij
    merging
    [2, 4] and [1]
    written
    1
    added
    +2
    count
    2

    3The second merge joins [2, 4] and [1]. The right front 1 is smaller than the left front 2, so it is smaller than both 2 and 4 still waiting. We add mid - i + 1 = 2.

  4. 1021423354
    merging
    [2, 4] and [1]
    written
    1 2 4
    added
    0
    count
    2

    4The right half is used up, so 2 and 4 are copied after the 1. The left part of the array now reads 1, 2, 4.

  5. 1021423354
    merging
    [3] and [5]
    written
    3 5
    added
    0
    count
    2

    5The third merge joins [3] and [5]. 3 is not bigger than 5, so they are written in order and the count stays 2.

  6. 1021423354ij
    merging
    [1, 2, 4] and [3, 5]
    written
    1
    added
    0
    count
    2

    6The last merge joins [1, 2, 4] and [3, 5]. The front 1 is not bigger than 3, so we write 1. A left value written first adds nothing.

  7. 1021423354ij
    merging
    [1, 2, 4] and [3, 5]
    written
    1 2
    added
    0
    count
    2

    7The front 2 is not bigger than 3 either, so we write 2 and move i on to the 4.

  8. 1021423354ij
    merging
    [1, 2, 4] and [3, 5]
    written
    1 2 3
    added
    +1
    count
    3

    8Now 3 is smaller than the left front 4, and only the 4 is still waiting on the left, so we add mid - i + 1 = 2 - 2 + 1 = 1 and write 3.

  9. 1021423354ij
    merging
    [1, 2, 4] and [3, 5]
    written
    1 2 3 4
    added
    0
    count
    3

    9The left front 4 is not bigger than the right front 5, so we write 4. The left half is now used up.

  10. 1021324354
    merging
    done
    written
    1 2 3 4 5
    added
    0
    count
    3

    10Only 5 is left, and it is written last. The array is sorted as 1, 2, 3, 4, 5, and countInversions returns 3.

Let us read the two frames where the count grows. In the second merge, the right value 1 goes first while both 2 and 4 wait on the left, so one step adds 2, covering (2, 1) and (4, 1) together. That is the bulk counting at work; the brute force needed two separate comparisons for those pairs.

In the last merge, 1 and 2 are written first and add nothing, because each is not bigger than the right front 3. Then 3 goes before the 4, with only the 4 waiting, so we add 1 for (4, 3). The total is 3, the same as our hand count, and as a side effect the array has come out sorted.

6The complete Java program

Here is the full program. countInversions sorts a clone so that the caller's array is left alone, and all merges share one buffer, a spare array of the same length. main counts our example, a reversed array, a sorted one, one with a repeated value, and a reversed array of a hundred thousand values.

Java
public class CountInversions {
// Number of pairs i < j with a[i] > a[j], counted during a merge sort of a copy.
static long countInversions(int[] input) {
int[] a = input.clone(); // leave the caller's array unchanged
return sortAndCount(a, new int[a.length], 0, a.length - 1);
}
private static long sortAndCount(int[] a, int[] buffer, int lo, int hi) {
if (lo >= hi) return 0;
int mid = lo + (hi - lo) / 2;
long count = sortAndCount(a, buffer, lo, mid) // inversions inside the left half
+ sortAndCount(a, buffer, mid + 1, hi); // inversions inside the right half
for (int k = lo; k <= hi; k++) buffer[k] = a[k];
int i = lo, j = mid + 1;
for (int k = lo; k <= hi; k++) {
if (i > mid) a[k] = buffer[j++];
else if (j > hi) a[k] = buffer[i++];
else if (buffer[j] < buffer[i]) {
count += mid - i + 1; // buffer[j] is smaller than every left element still waiting
a[k] = buffer[j++];
} else a[k] = buffer[i++]; // equal values are not an inversion
}
return count;
}
public static void main(String[] args) {
System.out.println(countInversions(new int[] {2, 4, 1, 3, 5})); // 3
System.out.println(countInversions(new int[] {8, 4, 2, 1})); // 6
System.out.println(countInversions(new int[] {1, 2, 3})); // 0
System.out.println(countInversions(new int[] {2, 2, 1})); // 2
int[] big = new int[100_000];
for (int i = 0; i < big.length; i++) big[i] = big.length - i; // fully reversed
System.out.println(countInversions(big)); // 4999950000
}
}

Let us read it in the order it runs. countInversions makes the copy and the buffer and calls sortAndCount on the whole range, lo = 0 to hi = a.length - 1. In sortAndCount, a range of one value or none has no inversions, so it returns 0; that is where the recursion stops.

Otherwise we find mid, written as lo + (hi - lo) / 2 so that the sum can never overflow, and the two recursive calls count and sort the left part lo..mid and the right part mid + 1..hi. Their counts go into count, which is a long. Then we copy the range into buffer, because the merge will overwrite a while it still needs the old values.

The merge loop fills a[k] for every k from lo to hi. If i has passed mid, the left half is used up, so we take from the right. If j has passed hi, the right half is used up, so we take from the left. Otherwise we compare the fronts. Only when buffer[j] < buffer[i], strictly smaller, do we add mid - i + 1 and take the right value. In every other case, ties included, we take the left value and add nothing.

For the reversed array of 100,000 values the answer is 100,000 times 99,999 divided by 2, which is 4,999,950,000, more than twice the largest int. That is why count, the return types and the additions are all long. So main prints 3, 6, 0, 2 and 4999950000.

7How much it costs, and the arrays at the edges

Let us count on the example first. The merges wrote 2, 3, 2 and 5 values, twelve writes in three levels of splitting. In general merge sort halves the range again and again, so there are about log2 n levels, where log2 n is the number of times n can be halved before reaching 1. On each level the merges together handle every value once, and the count is added in O(1) per step, so the time is O(n log n). For a hundred thousand values that is about 1.7 million steps instead of five billion.

For space, we use the copy and the buffer, two arrays of n values, plus one waiting call per level of recursion, which is O(log n). So the extra space is O(n).

Comparing the ways to count inversions
ApproachTimeExtra space
Check every pairO(n^2)O(1)
Merge sort with a cross countO(n log n)O(n)
Fenwick tree over value ranksO(n log n)O(n)

The edge cases need no special code. An empty array or a single value returns 0, because the recursion stops at once. A sorted array never takes a right value before a waiting left one, so it returns 0, and a reversed array returns n(n - 1)/2, as main shows with 6 for [8, 4, 2, 1]. With repeats, [2, 2, 1] gives 2, because both 2s form an inversion with the 1 but not with each other, thanks to taking the left value on a tie. And the caller's array is unchanged, because we sorted a clone.

8Follow-up questions

How would you count the pairs where a[i] > 2 * a[j]?

These are often called reverse pairs, and the same merge sort works, but the count cannot ride on the merge comparison, because the condition is different from the sort order. So before merging two sorted halves we make a separate pass. For each left value, we move a pointer through the right half while the left value is bigger than twice the right value, and add how far the pointer has moved. Both halves are sorted, so the pointer only moves forward, the pass is linear, and the total stays O(n log n). We double the value as a long, so the doubling cannot overflow.

What does the inversion count say about sorting?

It is exactly the number of swaps of neighbours needed to sort the array, because each such swap fixes one inversion and no more. So it is the number of swaps bubble sort performs and the number of shifts insertion sort performs. That is why insertion sort is quick on a nearly sorted array, since its time is O(n + inversions). For our photograph, it is the number of times two neighbouring children must change places before the line is in order, three for our example.

9Conclusion

We counted the inversions of an array with a merge sort that counts as it sorts. Each half counts and sorts its own inversions, and the cross pairs, which do not depend on the order inside either half, are counted in bulk during the merge by adding mid - i + 1 whenever a right value goes before a waiting left one. It takes O(n log n) time and O(n) space, with the total in a long. The clue to remember is counting pairs i < j that are out of order: think of merge sort and count across the halves.

What to say in the interviewAbout 90 seconds aloud

Open with

Let me confirm the definition. An inversion is a pair i less than j with a of i strictly greater than a of j, so equal values do not count.

Then, if they want more

The array can be large and I should not change it. The count can reach about n squared over two, so I will return a long. The brute force checks every pair with two loops, which is O(n squared). Since we count pairs that are out of order, I will use merge sort.

Every inversion is inside the left half, inside the right half, or across the halves. The recursive calls count the first two and sort the halves, and sorting inside a half does not change which values are on which side, so the cross pairs are kept.

During the merge, when the right front is smaller than the left front, it is smaller than every left value still waiting, because the left half is sorted, so I add mid minus i plus one and take the right value. On a tie I take the left value, so equal pairs are never counted.

That is O(n log n) time and O(n) space for a copy and one buffer. I would test an empty array, a sorted one, a reversed one, and repeated values.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 15 times in that collection. How it is counted
Official documentation
java.util, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Count the inversions in an array of integers.": https://scrivio-interview-library.netlify.app/data-structures/solutions/count-the-inversions-in-an-array-of-integers-e49964/