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] and b = [1, 2, 3], the output should be
    solution(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
    solution(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
    solution(a, b) = false.Any swap of any two elements either in a or in b won’t make a and b 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 and b 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 and b –> 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;
}
Leave a Reply 0

Your email address will not be published. Required fields are marked *