I know that the number of inversions in an n-element array can be counted in O(n log(n)) operations using an enhanced merge sort.
However, I came across a different solution, which somehow manages to count the number of inversions in O(n) time, provided that the input is a permutation of (1, 2, 3, ..., n−1, n):
EDIT:-
I am sorry for the code I pasted as it doesn't work in all the cases . Actually this code was used for this question and it passed all the cases . But I am still leaving the code so that it may serve as some intuition and maybe a linear time solution for this problem will come up.
NOTE :- The Below Mentioned Code is Incorrect.
/* int in = 0;
for (int i = 0; i < n; i++) {
a[i] = a[i] - i - 1;
}
for (int i = 0; i < n; i++) {
if (a[i] > 0)
in = in + a[i];
else if (a[i] < -1)
in = in - a[i] - 1;
} */
Now the question is can we come up with a linear time solution for this problem ?