InferenceAI

Enter at least two characters to search.

Start free

Count Inversions

hardBinary Search40 min50 XP

An inversion is a pair of indices i<ji < j with nums[i] > nums[j]. Return the number of inversions.

Requirements

  • O(nlog⁡n)O(n \log n) with a modified merge sort.

Constraints

  • 0≤n≤1050 \le n \le 10^5

Examples

EXAMPLE WALKTHROUGHthree inversions

A guided view of the published example, not a trace of your code.

INPUT[[2,4,1,3,5]]
TASKcount_inversions()
EXPECTED OUTPUT3

Start with the input values shown in this example.

Example 1 of 3

Input: nums = [2,4,1,3,5]

Output: 3

Explanation: three inversions

Input: nums = [1,2,3]

Output: 0

Explanation: sorted

Input: nums = [3,2,1]

Output: 3

Explanation: reversed

Hint 1

While merging two sorted halves, when an element from the right half is taken first, it forms an inversion with every remaining element of the left half.

Topics

DSABinary SearchPython