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?
Your code is not working because you sorted the original arrays here ...
copyA = A, copyB = B;
Arrays.sort(copyA); Arrays.sort(copyB);
then you are comparing the sorted arrays instead of original arrays for checking if they can be converted using only one swap!!
You should do something like this...
boolean areSimilar(int[] A, int[] B) {
if(A.length != B.length) return false;
int countSwap = 0;
int[] copyA = Arrays.copyOf(A, A.length);
int[] copyB = Arrays.copyOf(B, B.length);
// checking both contain the same elements...
Arrays.sort(copyA); Arrays.sort(copyB);
if(!Arrays.equals(copyA, copyB)) return false;
// checking for min 2 swaps using original arrays...
for(int i = 0; i < A.length; i++) {
if(A[i] != B[i]) countSwap++;
}
return (countSwap == 2 || countSwap == 0);
}
more efficient solution ...
boolean areSimilar(int[] A, int[] B) {
ArrayList<Integer> ids = new ArrayList<>();
for (int i = 0; i < A.length; i++) {
if ( A[i] != B[i] ) {
ids.add(i);
}
}
if (ids.size() == 0) {
return true;
}
if (ids.size() != 2) {
return false;
}
int id1 = ids.get(0);
int id2 = ids.get(1);
if (A[id1] == B[id2] && A[id2] == B[id1]) {
return true;
}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With