Are Similar

Description


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 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.

Input/Output

  • [execution time limit] 4 seconds (js)

  • [input] array.integer b

Array of integers of the same length as a.

Guaranteed constraints: b.length = a.length, 1 ≤ b[i] ≤ 1000.

  • [output] boolean

true if a and b are similar, false otherwise.

[JavaScript (ES6)] Syntax Tips

1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
    console.log("This prints to the console when you Run Tests");
    return "Hello, " + name;
}

Solution


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function areSimilar(a, b) {
    var sw = 0;
    var t;
    var ar;
    var br;
    var ret = true;
    for (var i = 0; i < a.length; i++) {
        if(a[i] === b[i])
            continue;
        if(sw === 0){
            sw++;
            ar = a[i];
            br = b[i];
            ret = false;
        }
        else {
            if (ar !== b[i] || br !== a[i])
                sw++;
            else {
                ret = true;
                sw++;
            }
        }
    }
    
    return ret && (sw === 0 || sw === 2);       
}