Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Count Inversions

Medium Acceptance 16.93% Points 30

Given an array of integers arr[]. Find the Inversion Count in the array.

Two elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j.

Inversion Count: For an array, inversion count indicates how far (or close) the array is from being sorted. If the array is already sorted then the inversion count is 0. If an array is sorted in the reverse order then the inversion count is the maximum.

Examples
Example 1

Example 1

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

Output: 3

Explanation: The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3).

Example 2

Example 2

Input: arr[] = [2, 3, 4, 5, 6]

Output: 0

Explanation: As the sequence is already sorted so there is no inversion count.

Constraints
  • 1 <= arr.size() <= 10^5
  • 1 <= arr[i] <= 10^4
Hints
  • Expected Time Complexity: O(n log n)
  • Expected Space Complexity: O(n)
Topics
Array Sorting Algorithms
Companies
Amazon Microsoft Adobe Flipkart Myntra
Added 19 Jul 2026 16.93% acceptance
Ln 1, Col 1Sign in to save your code
2 4 1 3 5
3