Concepts

Sorted two-pointer pair search

Try the free JavaScript compiler

Find two distinct positions in a sorted array by discarding one endpoint at a time using the sum comparison.

Formal Syntax & Structure

javascript syntaxjavascript
pair(sortedValues, target) → [left,right] | null

Working Example

Example Snippetjavascript
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)));
JavaScript Reference