Hard 0 solved 0% acceptance

Count Inversions

Count the out-of-order pairs in a list.

What you'll learn

  • Count out-of-order pairs while merging
  • Extend merge sort with extra counting
  • Go from O(n²) to O(n log n)

Problem

An inversion is a pair of positions i < j with numbers[i] > numbers[j]. Count all inversions. Lists can be long, so a merge-sort based O(n log n) count is needed.

Implement count_inversions(numbers).

Input

numbers: The list of integers.

Output

Return the number of inversions.

Constraints

0 ≤ length ≤ 200,000

Examples

Example 1
Input:
numbers = [2, 4, 1, 3, 5]

Expected output:
expected = 3
Input:
std::vector<long long> numbers = {2, 4, 1, 3, 5};

Expected output:
long long expected = 3;
Input:
long[] numbers = new long[] {2, 4, 1, 3, 5};

Expected output:
long expected = 3;

Explanation

Out-of-order pairs: (2,1), (4,1), (4,3): 3 inversions.

Example 2
Input:
numbers = [1, 2, 3]

Expected output:
expected = 0
Input:
std::vector<long long> numbers = {1, 2, 3};

Expected output:
long long expected = 0;
Input:
long[] numbers = new long[] {1, 2, 3};

Expected output:
long expected = 0;

Explanation

Already sorted: 0 inversions.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

An inversion is counted when a left-side number stays larger than a right-side number during merging.

Hint 2

Split the list recursively and count cross-pairs while merging sorted halves.

Hint 3

Be careful with duplicates: equal values are not inversions, so the comparison direction matters.

Expected complexity

O(n log n) time, O(n) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.