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.
Input: [1]
Expected Output: 0
Explanation: A single element has no pair to compare against.
Input: [1, 2, 3, 4, 5]
Expected Output: 0
Explanation: A fully ascending array has no inversions.
Input: [5, 4, 3, 2, 1]
Expected Output: 10
Explanation: A strictly descending array of length 5 has the maximum 5*4/2 = 10 inversions.
Input: [2, 2, 2, 2]
Expected Output: 0
Explanation: Equal elements are not inversions (the condition is strict arr[i] > arr[j]).
Input: [-1, -3, 5, -2, 0]
Expected Output: 4
Explanation: Inversions: (-1,-3),(-1,-2),(5,-2),(5,0).
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.