Home > Net >  CodeSignal Arcade level-4-16:"Are Similar?"
CodeSignal Arcade level-4-16:"Are Similar?"

Time:01-22

i passed all test cases,
but i failed in hidden casese.
I really can't find error cases and what's wrong with my code.
please help me

The question was as follows:

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

) Guaranteed constraints: b.length = a.length

This is my code:

boolean solution(int[] a, int[] b) {
    
    int count = 0;
    ArrayList<Integer> tempa = new ArrayList<>();
    ArrayList<Integer> tempb = new ArrayList<>();
    
    for(int i = 0; i < a.length; i  ){
        if(a[i]!=b[i]){
            
            count  ;
            
            tempa.add(a[i]);
            tempb.add(b[i]);
        }
        
    }
    
    if(count==0||(count==2 && tempa.get(0)==tempb.get(1) && tempa.get(1)==tempb.get(0))){
        return true;
    } else return false;
}

This code gave correct results for the following arrays:

a: [1, 2, 3]
b: [1, 2, 3]

a: [1, 2, 3]
b: [2, 1, 3]

a: [1, 2, 2]
b: [2, 1, 1]

a: [1, 2, 1, 2]
b: [2, 2, 1, 1]

a: [1, 2, 1, 2, 2, 1]
b: [2, 2, 1, 1, 2, 1]

a: [1, 1, 4]
b: [1, 2, 3]

a: [1, 2, 3]
b: [1, 10, 2]

a: [2, 3, 1]
b: [1, 3, 2]

a: [2, 3, 9]
b: [10, 3, 2]

a: [832, 998, 148, 570, 533, 561, 894, 147, 455, 279]
b: [832, 570, 148, 998, 533, 561, 455, 147, 894, 279]

CodePudding user response:

You need to add this for diferent arrays length

if (a.length != b.length) return false;

And your if needs to use equals()

return count == 0 || (count == 2 && tempa.get(0).equals(tempb.get(1)) && tempa.get(1).equals(tempb.get(0)));

CodePudding user response:

Here's an example where it fails:

solution(new int[]{2, 3, 9}, new int[]{9, 3, 2, 5});

You should add a length equality check to your code, like this

static boolean solution(int[] a, int[] b) {
    if(a.length != b.length) {
        return false;
    }
    ...
}
  •  Tags:  
  • java
  • Related