Hi Design Guru,

Could you give me simple explanation to understand why we are taking differences instead of just incrementing the counter.

count += right - left;

Hi Design Guru,

Could you give me simple explanation to understand why we are taking differences instead of just incrementing the counter.

count += right - left;

3 Likes

curious about this as well

Not sure if this helps or not (i’m still trying to figure it out myself haha) but:

I think that since we’ve sorted the list we know that if the current sum is less than the target, then all the sums in between should be too.

Ex) list is [-1,1,2,3,4] target = 6

When the left pointer is 1 and right pointer is 4, the sum (-1 + 1 + 4) is less than the target. So we know that (-1 + 1 + 2) and (-1 + 1 + 3) would also be smaller than the target.

3 Likes