Funcia
Lv.3divide-and-conquerfenwick-treesorting

Count Inversions

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

Given an integer array nums, count the pairs i < j with nums[i] > nums[j] (equal values are not inversions).

Examples

numsresult
[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

  • 1≤1 \le nums.length ≤200,000\le 200{,}000, −109≤-10^9 \le nums[i] ≤109\le 10^9
  • The answer can reach about 2×10102 \times 10^{10}; use a 64-bit integer.

Expected complexity

Time
O(N log N)
Space
O(N)

Examples

numsExpected
[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 O(N2)O(N^2) and exceeds the time limit.

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251164 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness409verdict only
performance604verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.