Two-pointer search on sorted arrays
Quick answer
Two pointers are indices advanced according to an invariant. On ascending numeric arrays, opposite ends can find a pair whose sum equals a target without examining every pair.
Working examples
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
function pair(a,target){ let l=0,r=a.length-1; while(l<r){ const s=a[l]+a[r]; if(s===target)return [l,r]; if(s<target)l++;else r--; } return null;}console.log(JSON.stringify(pair([-3,0,2,4,7],4)));Expected console output:
[0,4]The endpoints sum to four.
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
function hasPair(a,target){ let l=0,r=a.length-1; while(l<r){const s=a[l]+a[r];if(s===target)return true;if(s<target)l++;else r--;} return false;}console.log(hasPair([2],4),hasPair([2,2],4));Expected console output:
false trueDistinct indices are necessary, not distinct values.
How it works and cost model
Start left at zero and right at length - 1. If their sum is too small, the left value paired with any smaller right value cannot reach the target, so advance left. If too large, decrease right. Stop when equal or when left >= right. The indices must be distinct. For bounded safe integers, O(n) comparisons and O(1) auxiliary space suffice. Sorting unsorted input first incurs cost and can change original indices; preserve indices if needed.
Common mistakes
The discard rule depends on sorted order. Do not use the same element twice when only one occurrence exists.
Practice
Find a pair of distinct indices in [-3,0,2,4,7] summing to 4, then test [2] and [2,2] for target 4.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Two-pointer search on sorted arrays — Knowledge Check
Reason about the algorithm or data structure, its invariants, trade-offs and deterministic outputs.
Why advance the left index when the endpoint sum is below the target?
What is the purpose of the condition left < right?
What extra concern arises when sorting an unsorted input for pair-index lookup?
What is the exact console output in the Sorted two-pointer pair search example 1?
function pair(a,target){ let l=0,r=a.length-1; while(l<r){ const s=a[l]+a[r]; if(s===target)return [l,r]; if(s<target)l++;else r--; } return null;}console.log(JSON.stringify(pair([-3,0,2,4,7],4)));What is the exact console output in the Sorted two-pointer pair search example 2?
function hasPair(a,target){ let l=0,r=a.length-1; while(l<r){const s=a[l]+a[r];if(s===target)return true;if(s<target)l++;else r--;} return false;}console.log(hasPair([2],4),hasPair([2,2],4));