CodeSignal Arcade – Are Similar?
Problem
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 a
and b
, check whether they are similar.
Example
- For
a = [1, 2, 3]
andb = [1, 2, 3]
, the output should besolution(a, b) = true
.The arrays are equal, no need to swap any elements. - For
a = [1, 2, 3]
andb = [2, 1, 3]
, the output should besolution(a, b) = true
.We can obtainb
froma
by swapping2
and1
inb
. - For
a = [1, 2, 2]
andb = [2, 1, 1]
, the output should besolution(a, b) = false
.Any swap of any two elements either ina
or inb
won’t makea
andb
equal.
Solution
Idea
The key point of this problem is translating swapping at most one pair of elements in one of the arrays
into coding solution. How do you understand it?
- If
a
andb
are the same, they have 0 different element. –> true - If a and b have 1 different element, it cannot be swapped. –> false
- If a and b have 2 different elements:
- those 2 elements can be swapped. –> true
- those 2 elements are different in
a
andb
–> false. Example:a = [1, 2, 4], b = [1, 4, 1].
- If a and b have 3 different elements, we need more than 1 swapping round to make them the same. –> when different elements count equals or greater than 3, the result is always false.
After understanding the problem correctly, it’s easy. Firstly, I count the differences between a
and b
. If the count is greater than 2, return false
. Also, I store the different number into an array. After that I remove the duplicate numbers. The number of remaining numbers should be equal to number of differences.
Code
function solution(a, b) {
let diffCount = 0;
let diffArr = [];
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
diffCount++;
diffArr.push(a[i]);
diffArr.push(b[i]);
}
if (diffCount > 2) {
return false;
}
}
// remove duplicated element
let uniq = [...new Set(diffArr)];
return uniq.length == diffCount;
}