Lv.3divide-and-conquerfenwick-treesorting
Count Inversions
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Given an integer array nums, count the pairs i < j with nums[i] > nums[j] (equal values are not inversions).
Examples
| nums | result |
|---|---|
[2, 4, 1, 3, 5] | 3 |
[5, 4, 3, 2, 1] | 10 |
[7, 7, 7] | 0 |
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(nums: int[]) → long
Constraints
-
nums.length,nums[i] - The answer can reach about ; use a 64-bit integer.
Expected complexity
- Time
- O(N log N)
- Space
- O(N)
Examples
| nums | Expected |
|---|---|
[2,4,1,3,5] | 3 |
[5,4,3,2,1] | 10 |
[7,7,7] | 0 |
Hint
Hint
Count while merge sorting (when the right element is emitted first, every remaining left element is larger; emit the left one first on ties), or use a Fenwick tree over compressed values. Comparing all pairs is and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1164 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 9 | verdict only |
| performance | 60 | 4 | verdict only |