Two Sum on a sorted array
JavaScriptfunction twoSum(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left < right) {
const sum = arr[left] + arr[right];
if (sum === target) return [left, right];
if (sum < target) left++;
else right--;
}
return [];
}
console.log(twoSum([1, 3, 4, 5, 7, 9, 11], 9));Explanation
left starts at the smallest number and right starts at the largest. If the sum is too small, left moves right to increase it. If the sum is too large, right moves left to decrease it. Because the array is sorted, each move is logically safe.
Output
[2, 3]
Real-life Example
If a finance app needs two sorted expense values whose total matches a target reimbursement amount, two pointers find the pair without checking every combination.