Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Count Inversions

Medium Acceptance 16.93% Points 30.00

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.

Hints
Hint 1
Expected Time Complexity: O(n log n)
Hint 2
Expected Space Complexity: O(n)
Constraints
  • 1 <= arr.size() <= 10^5
  • 1 <= arr[i] <= 10^4
Companies
Amazon Microsoft Adobe Flipkart Myntra
Topics
Array Sorting Algorithms
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions