Skip to content

Are Similar?

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

    are_similar(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

    are_similar(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

    are_similar(a, b) = false

    Any swap of any two elements either in a or in b won't make a and b equal.

Solution

py
def are_similar(a, b):
    return sorted(a) == sorted(b) and sum([i != j for i, j in zip(a, b)]) <= 2


print(are_similar([1, 2, 3, 4], [1, 3, 2, 4]))
js
// Input:
// a: [1, 2, 3]
// b: [2, 1, 3]

// Expected Output:
// true

function areSimilar(a, b) {
  if (a.length !== b.length) {
    return false;
  }
  let diff = 0;
  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) {
      diff++;
    }
  }
  if (diff > 2) {
    return false;
  }
  a.sort();
  b.sort();
  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) {
      return false;
    }
  }
  return true;
}

print(areSimilar([1, 2, 3, 4], [1, 3, 2, 4]));

my thoughts are neither my employer's nor my wife's