Data Structures19 sections · 729 units
Open in Course

Two Pointers Logic

The decision rule

With pointers leftleft and rightright on a sorted array: If arr[left]+arr[right]<targetarr[left] + arr[right] < target: move leftleft right. The sum is too small, and moving leftleft increases it.

If arr[left]+arr[right]>targetarr[left] + arr[right] > target: move rightright left. The sum is too big, and moving rightright decreases it. If they're equal: you found the answer.

Each step eliminates at least one element from consideration. After at most nn steps, you've checked all possibilities.