Iram Shahed Iram Shahed - 1 month ago 6
Java Question

Trying to return the number of differences between two arrays

So if I have two arrays

int [] array1 = {1, 2, 3, 4}
int [] array2 = {1, 3, 2, 4}


This would return two as there are two differences in the arrays so far I have this but I can't figure it out.

public static int countDifferences(int[] array1, int[] array2){
int differences = 0;
for(int i=0; i<array1.length; i++) {
for(int j=0; j<array2.length; j++) {
if(array1[i]==array2[j]) {
return 0;
}
else{
differences++;
}
}
}
return differences;
}

Answer

You should just have a single for loop to iterate once over both arrays. You also need to handle the case where the two input arrays do not have the same length. Also, one or both arrays could be empty. For these edge cases I am returning -1, though you can modify if you want.

public static int countDifferences(int[] array1, int[] array2) {
    if (array1.length != array2.length || array1 == null || array2 == null) {
        return -1;
    }
    int differences = 0;

    for (int i=0; i < array1.length; i++) {
        if (array1[i] != array2[i]) {
            differences++;
        }
    }

    return differences;
}