I had a question about the first (Brute force) solution for the problem on Find Two Numbers that Add up to “n”.
The given explanation says
Traverse the whole array of the given size. For each element in the array, check if any of the two elements add up to the given number
n
. Use a nested for-loop for this purpose and iterate over the entire array for each element.
Specifically, the last line says we iterate over the entire array once for each element. I don’t think this is true.
Consider this array - [2, 4, 5, 7, 8]
.
- For the first iteration of the outer loop, we set
i
at the first element2
. Then for the inner loop, we setj
ati+1
, that is, we start checking from 4 up to 8. - For the next iteration of the outer loop, when
i
is at 4, we setj
ati+1
again, that is, we check from 5 till 8. We don’t again setj
at index 0 and traverse the entire array again, because2 + 4
has already been checked in the first step.
So why does the explanation say “iterate over the entire array for each element”?