How to avoid using a double loop to improve this method?

Viewed 103

I was asked in an interview to rewrite this method without the nested for-loop. All I knew apart from this was that the arrays are of the same size. What's a good way to approach this ?

public int addTwo(int[] first, int[] second) {
    int result = 0;
    for (int k : first) {
        for (int i : second) {
            result += k * i;
        }
    }
    return result;
}
1 Answers

If we remeber Matematics, if in first array we have k1, k2, k3, in second array we have i1,i2,i3, so result k1 * i1 + k1 * i2 + k1 * i3 + k2 * i1 + ...

So we can see, we should refactoring this math expression like k1 * (i1 + i2 + i3) + k2 * (i1 + i2 + i3) + k3 * (i1 + i2 + i3)

And k1 * (i1 + i2 + i3) + k2 * (i1 + i2 + i3) + k3 * (i1 + i2 + i3) = (k1 + k2 + k3) * (i1 + i2 + i3).

So you can refactoring your code as

public int addTwo(int[] first, int[] second) {
    int firstSum = 0;
    int secondSum = 0;

    for (int k : first) {
        firstSum += k;            
    }

    for (int i : second) {
        secondSum += i;
    }

    return firstSum * secondSum;
}
Related