I am looking for an algorithm to solve this problem:
Given 2 arrays, A and B which are both permutations of [1..n], what is the number of inversions between these 2?
An inversion here would be when a pair elements (i,j) this holds:
if A.indexOf(i) > A.indexOf(j) && B.indexOf(i) < B.indexOf(j)
or
if A.indexOf(i) < A.indexOf(j) && B.indexOf(i) > B.indexOf(j)
I know that there exist multiple ways to do this when you can assume the first array is sorted, like counting the inversions while doing MergeSort, but I have 2 non-sorted arrays.
Example:
A = [6,3,4,1,2,5] and B = [3,5,2,6,1,4]
No. of inversions = 9
6 has a lower index than 3 in A, but a higher index than 3 in B. This is an inversion.
I am hoping to achieve this in O(n log n) time complexity using a Divide and Conquer approach.