![]() |
VOOZH | about |
Given an array arr[], the goal is to count the number of inversions in all the sub-arrays. An inversion is a pair of indices i and j such that i > j and arr[i] < arr[j]. A sub-array from index x to y ( x<= y) consists of the element's arr[x], arr[x+1], ..., arr[y]. The array arr[] can also contain repeated elements.
Examples:
Input: arr[] = {3, 6, 1, 6, 5, 3, 9}
Output:
0 0 2 2 4 7 7
0 0 1 1 3 6 6
0 0 0 0 1 3 3
0 0 0 0 1 3 3
0 0 0 0 0 1 1
0 0 0 0 0 0 0
0 0 0 0 0 0 0
Explanation:
The element in the i'th row and j'th column of the output denotes the number of inversions from index i to j (inclusive). Consider i = 1 and j = 4 (assuming 0-based indexing), the number of inversions in the subarray {6, 1, 6, 5} is 3. The element pairs are (6, 1), (6, 5) and (6, 5) (from the second 6).Input: arr[] = {3, 2, 1}
Output:
0 1 3
0 0 1
0 0 0
Explanation:
From index 0 to 1 there is 1 inversion, from index 2 to 3 there is 1 inversion and from index 0 to 2 there are 3 inversions. The i'th row and j'th column of the output is 0 if i >= j.
Naive Approach: A naive approach is to generate all possible sub-arrays and count the number of inversions in each of the sub-arrays.
Below is the implementation of the above approach:
0 0 2 2 4 7 7 0 0 1 1 3 6 6 0 0 0 0 1 3 3 0 0 0 0 1 3 3 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Time Complexity: O(N4)
Auxiliary Space: O(N2)
Efficient Approach: The above method can be optimized a little using the method given here to find the number of inversions in a sub-array. First see some observations to solve this problem:
First create a 2d array greater[][], where greater[i][j] denotes the number of elements in the range i to j which are greater than arr[i]. Iterate over the array and for each element, find the number of elements to its right which are less than the element. This can be done using a naive approach in O(N^2). Now to find the number of inversions in a range say x to y, the answer will be greater[x][y] + greater[x+1][y] + ... + greater[y-1][y] + greater[y][y].
With the greater[][] table this value can be calculated in O(n) for each sub-array resulting in a complexity of O(n^3).(There are O(n^2) sub-array, and it takes O(n) time to compute the number of inversions in each sub-array). To find this value in O(1) each time build a prefix sum table from the greater[][] table where prefix[i][j] denotes the value of greater[0][j] + greater[1][j] + ... + greater[i][j]. This table can also be built in O(N^2) time. Now the answer for each sub-array from x to y (inclusive) would become prefix[y][y] - prefix[x-1][y] if x >= 1 and prefix[y][y] if x = 0.
Follow the step below to solve this problem:
Below is the implementation of the above approach:
0 0 2 2 4 7 7 0 0 1 1 3 6 6 0 0 0 0 1 3 3 0 0 0 0 1 3 3 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Time Complexity: O(N2)
Space Complexity: O(N2)