Hard 0 solved 0% acceptance

Count Inversions

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

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.

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.