Count inversions in an array efficiently
Company: Akuna Capital
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates understanding of inversion counting and algorithmic design, specifically comparing naive O(n^2) approaches with O(n log n) divide-and-conquer strategies while requiring analysis of time and space complexity.
Constraints
- 0 <= len(arr) <= 10^5
- -10^9 <= arr[i] <= 10^9
- Array elements may contain duplicates and negative numbers
- Equal elements (arr[i] == arr[j]) do NOT form an inversion
Examples
Input: [5, 7, 9, 2, 3, 12, 8, 4]
Expected Output: 13
Explanation: The 13 inversion pairs include (5,2),(5,3),(5,4),(7,2),(7,3),(7,4),(9,2),(9,3),(9,8),(9,4),(12,8),(12,4),(8,4).
Input: []
Expected Output: 0
Explanation: An empty array has no pairs, so 0 inversions.
Hints
- The naive solution is a double loop over all pairs (i, j) with i < j, counting when arr[i] > arr[j]. This is O(n^2) and a correct baseline.
- To get O(n log n), modify merge sort. The total inversion count equals inversions within the left half, plus inversions within the right half, plus cross-half inversions discovered during the merge.
- During the merge of two sorted halves, when you pick an element from the RIGHT half (because it is smaller than the current LEFT element), every remaining element in the left half is greater than it — add (number of remaining left elements) to the count.