Two Pointers Technique
DSA · Arrays & Stringssyntax
Use two indices (left and right) moving toward each other or in the same direction.
Works on sorted arrays or when searching for pairs.example
// JavaScript — Find pair that sums to target in sorted array
function twoSumSorted(arr, target) {
let left = 0, right = arr.length - 1;
while (left < right) {
const sum = arr[left] + arr[right];
if (sum === target) return [left, right];
else if (sum < target) left++;
else right--;
}
return [-1, -1];
}
# Python
def two_sum_sorted(arr, target):
left, right = 0, len(arr) - 1
while left < right:
total = arr[left] + arr[right]
if total == target:
return [left, right]
elif total < target:
left += 1
else:
right -= 1
return [-1, -1]output
twoSumSorted([1,3,5,7,9], 8) → [1, 3]Note Time O(n), Space O(1). Requires sorted input for the converging pattern. Edge cases: empty array, single element, no valid pair. Tell the interviewer you chose two pointers over hash map to achieve O(1) space.