I got this coding problem from a website. The question was as follows:
Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.
Given two arrays, check whether they are similar.
Example
For A = [1, 2, 3] and B = [1, 2, 3], the output should be areSimilar(A, B) = true.
The arrays are equal, no need to swap any elements.
For A = [1, 2, 3] and B = [2, 1, 3], the output should be areSimilar(A, B) = true.
We can obtain B from A by swapping 2 and 1 in B.
For A = [1, 2, 2] and B = [2, 1, 1], the output should be areSimilar(A, B) = false.
Any swap of any two elements either in A or in B won't make A and B equal.
This is the solution I gave:
boolean areSimilar(int[] A, int[] B) {
if(A.length != B.length) return false;
int[] copyA = A, copyB = B;
Arrays.sort(copyA); Arrays.sort(copyB);
int countSwap = 0;
if(!Arrays.equals(copyA, copyB)) return false;
for(int i = 0; i < A.length; i++) {
if(A[i] != B[i]) countSwap++;
}
return (countSwap == 2 || countSwap == 0);
}
This code gave correct results for the following arrays:
A: [1, 2, 3]
B: [1, 2, 3]A: [1, 2, 3]
B: [2, 1, 3]A: [1, 2, 2]
B: [2, 1, 1]A: [1, 1, 4]
B: [1, 2, 3]A: [1, 2, 3]
B: [1, 10, 2]A: [2, 3, 1]
B: [1, 3, 2]
But still the website displays "INCORRECT" every time I try to submit the code. It fails to pass two out of six hidden tests and I cannot figure out why. Is this the correct code? Is there any other, more easier way?