Data Structures19 sections · 729 units
Open in Course

Count Inversions Solution

Implement your solution

Implement inversion counting with BIT. Core idea: an inversion (i,j)(i, j) with i<ji < j and a[i]>a[j]a[i] > a[j] means a[i]a[i] is "out of order" relative to a[j]a[j].

Processing right to left: when you see a[i]a[i], all elements you've added to the BIT are to the right of position ii.

Querying for elements smaller than a[i]a[i] counts exactly those forming inversions with a[i]a[i]. Alternative: use merge sort to count inversions. Both approaches are O(nlogn)O(n \log n).

BIT is often simpler for competitive programming. Time: O(nlogn)O(n \log n). Space: O(n)O(n).