1. Both ends
Start at the smallest and largest values.
let left = 0;
let right = numbers.length - 1Typorithm · medium
Step 1 of 8 · intro card
Two Pointers
On a sorted array, move left up when the pair sum is too small and right down when too big until it hits the target.
Because the input is sorted, the sum of the two endpoints guides the search.
If the sum is too small, only a larger left value can help, so advance left.
If too large, only a smaller right value can help, so retreat right — each step rules out a row or column of pairs.
Requires sorted input.
Sum too small → left up.
Sum too big → right down.
function twoSum(numbers, target) {
let left = 0;
let right = numbers.length - 1;
while (left < right) {
const sum = numbers[left] + numbers[right];
if (sum === target) {
return [left + 1, right + 1];
}
if (sum < target) {
left += 1;
} else {
right -= 1;
}
}
return [];
}Connect each part of the code to the concept before you type.
Start at the smallest and largest values.
let left = 0;
let right = numbers.length - 1Evaluate the sum of the current endpoints.
const sum = numbers[left] + numbers[right]Too small, so move left up to a larger value.
if (sum < target) {
left += 1;
}Return the found indices, converted to 1-based.
return [left + 1, right + 1]Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.