How to swap one pair of elements in an array and check to see if they are equal?
I am trying to write code for a javascript problem on CodeFights.
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.
This is what I have come up with so far. The problem that I have ran into is that this code does not pass all of the test.
function areSimilar(a, b) {
if (a.join() === b.join()) {
return true;
}
for (var i = 0; i < a.length-1; i++) {
for (var j = 1; j < a.length; j++) {
if (swap(a, i, j).join()=== b.join()) {
return true;
}
}
}
return false;
}
function swap(target, start, end) {
var temp = target[start];
target[start] = target[end];
target[end] = temp;
return target;
}
If I add the following code to line 10 (after the if statement), it does past the test but not the output time:
console.log(swap(a,i,j));
If someone could point me into the right direction of what to research / why this is happening, I am would greatly appreciate it.
Solution 1:
Here's a O(n) time and O(n) space solution
function areSimilar(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
let diff = [];// initialize array that'll be used to track indices where values differ
for (let i = 0; i < arr1.length; i++) {// loop thru first array
if (arr1[i] !== arr2[i]) { //check for value differences between arrays at each index
diff.push(i); //if the values differ push index into diff array
if (diff.length > 2) return false;
if (diff.length === 2) {
// use the diff array indices to swap, if swapped pairs are not eqaul return false;
if (arr1[diff[0]] !== arr2[diff[1]] || arr1[diff[1]] !== arr2[diff[0]]) {
return false;
}
}
}
}
//if it makes it through all of that
return diff.length === 0 || diff.length === 2;
}
console.log(areSimilar([1, 2, 3, 4], [1, 3, 2, 4]));
console.log(areSimilar([1, 2, 3, 4, 5], [1, 3, 2, 5, 4]));
console.log(areSimilar([1, 2, 6, 4, 5], [1, 2, 3, 5, 4]));