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
iat the first element
2. Then for the inner loop, we set
i+1, that is, we start checking from 4 up to 8.
- For the next iteration of the outer loop, when
iis at 4, we set
i+1again, that is, we check from 5 till 8. We don’t again set
jat index 0 and traverse the entire array again, because
2 + 4has already been checked in the first step.
So why does the explanation say “iterate over the entire array for each element”?