Is this a general algorithmic question, or are you asking for a specific (language-based) implementation?
For question #1, simply sort each array in O(nlog(n))
and then compare the arrays in O(n)
.
If the range of input values is not significantly large, then you can use a direct hash table instead and perform the sorting phase in O(n)
, thus reducing the overall complexity from O(nlog(n))
to O(n)
.
In Java, you can achieve this using a HashMap
instance. I'm not sure about the internal implementation of this class, but it might achieve the same performance even for a large range of input values.
For question #2, since there are no repetitive elements, the total number of permutations is n!
.
You can calculate the permutation-ID of each array within the entire group of permutations, and then use the pair of IDs that you have calculated in order to uniquely identify the mapping between the two arrays.
For example, suppose that A = {3,2,1,4}
and B = {4,1,3,2}
.
The total number of permutations is 24, so each permutation can be mapped to an ID between 0 and 23:
1,2,3,4 ==> 0
1,2,4,3 ==> 1
1,3,2,4 ==> 2
1,3,4,2 ==> 3
1,4,2,3 ==> 4
1,4,3,2 ==> 5
2,1,3,4 ==> 6
2,1,4,3 ==> 7
2,3,1,4 ==> 8
2,3,4,1 ==> 9
2,4,1,3 ==> 10
2,4,3,1 ==> 11
3,1,2,4 ==> 12
3,1,4,2 ==> 13
3,2,1,4 ==> 14
3,2,4,1 ==> 15
3,4,1,2 ==> 16
3,4,2,1 ==> 17
4,1,2,3 ==> 18
4,1,3,2 ==> 19
4,2,1,3 ==> 20
4,2,3,1 ==> 21
4,3,1,2 ==> 22
4,3,2,1 ==> 23
- Array
A
is mapped to ID 14
- Array
B
is mapped to ID 19
- The mapping f(A,B) = (14,19)
If you want this function to yield a single value, then you can use n!*id1+id2
instead of id1,id2
.
Alternatively, you can define the mapping function f(A,B) to return an array of index-changes.
For example, suppose that A = {3,2,1,4}
and B = {4,1,3,2}
.
- The element at index 0 moves to index 2, so the index-change is +2
- The element at index 1 moves to index 3, so the index-change is +2
- The element at index 2 moves to index 1, so the index-change is -1
- The element at index 3 moves to index 0, so the index-change is -3
Hence, f({3,2,1,4},{4,1,3,2})
should return the array {2,2,-1,-3}
.