956. Count Inversions Using BIT

HardTreesBITFenwick TreeMerge Sort

Given an integer array, return the number of inversions — pairs of indices (i, j) with i < j and nums[i] > nums[j]. Use a Binary Indexed Tree over compressed ranks (or a merge sort). The input is a JSON array.

Input: A JSON array of integers.

Output: Integer — the number of inversions.

Examples

Example 1
Input: [8,4,2,1]
Output: 6
Explanation: Every pair is inverted.
Example 2
Input: [1,2,3]
Output: 0
Explanation: Already sorted.
Example 3
Input: [2,1]
Output: 1
Explanation: One inversion.

Constraints

Asked by

AmazonGoogleMicrosoftMetaAdobe
Solve this problem in the editor →