Data Structures19 sections · 729 units
Open in Course

Problem - Count Inversions

Classic BIT application

Given an array, count the number of inversions: pairs (i,j)(i, j) where i<ji < j but a[i]>a[j]a[i] > a[j]. Example: [2,4,1,3,5][2, 4, 1, 3, 5] has 3 inversions: (2,1),(4,1),(4,3)(2,1), (4,1), (4,3).

Naive approach: check all pairs in O(n2)O(n^2). BIT approach: process right to left. For each element, query how many smaller elements you've seen so far (to the right).

This counts inversions. Constraints: up to 10510^5 elements.