Find two numbers in [1, 3, 5, 7, 11, 13, 17] that add up to 16. The simplest way, called brute force: try every pair one by one, 1 + 3, 1 + 5, and so on. By the time you reach 3 + 13, you have tried 10 pairs. Can you do better?
You can, with two pointers: two position markers in an array, moved by a rule. A pointer here is just a normal variable that holds an index, like left and right. In a sorted array (from small to big), two pointers from both ends can find a pair of numbers with a given sum. They walk through the array only once and don't try every pair. It's like two people searching a shelf from both ends and walking towards each other: the shelf is the array, and each person is one pointer.
Both ends moving closer
The target is 16. left starts at index 0 (the smallest number), right at the last index, 6 (the biggest number). In the table, the number in brackets is the array item at that index:
| Step | left (number) |
right (number) |
Sum | Decision |
|---|---|---|---|---|
| 1 | 0 (1) | 6 (17) | 18 | too big: right steps back |
| 2 | 0 (1) | 5 (13) | 14 | too small: left steps forward |
| 3 | 1 (3) | 5 (13) | 16 | a match: found |
Just 3 steps, while brute force needs 10 tries.
Here is the code, as a function named twoSum:
function 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]; // a match: return the positions
if (sum < target) left++; // too small: take a bigger number
else right--; // too big: take a smaller number
}
return null; // the pointers met: no pair
}
console.log(twoSum([1, 3, 5, 7, 11, 13, 17], 16)); // [1, 5]
console.log(twoSum([1, 3, 5, 7, 11, 13, 17], 19)); // null
leftstarts at0,rightatarr.length - 1, the last index.- Sum too small (smaller than the target):
left++, move to a bigger number. Sum too big:right--, move to a smaller number. - A match:
return [left, right], the positions of the two numbers, not the numbers.[1, 5]means index 1 (the number 3) and index 5 (the number 13). The Lab shows the numbers,[3, 13], while the exercise asks for the positions. while (left < right): once the two pointers meet, there are no pairs left to try, so the result isnull. The last line is an example: no two numbers add up to 19.
Why is moving allowed?
The array is sorted from small to big. In step 1, 1 + 17 = 18, too big. 1 is the smallest number, so 17 plus any other number is at least 18. 17 can't be part of the answer, so it's dropped: right--. In step 2, 1 + 13 = 14, too small. 13 is the biggest number left, so 1 plus any number left is at most 14. 1 is dropped too: left++. Every step drops one number that surely isn't part of the answer.
So n numbers take at most n - 1 steps, because the loop stops when one number is left. That's O(n): twice the data, roughly twice the steps. Brute force tries every pair with a loop inside a loop, and that's O(n²) (n times n): twice the data, roughly four times the work. The main condition: the array must be sorted. In an unsorted array, the reason for dropping a number doesn't hold.
Other options when the array is not sorted:
| Way | Time, extra memory | When to pick it |
|---|---|---|
| Two pointer | O(n), O(1) | the array is already sorted. This is the way in this lesson |
Map, one pass |
O(n), O(n) | the array is not sorted, and you need the original positions |
| Sort first, then two pointer | O(n log n), depends on the sort | not sorted, and you only need the numbers, because the original positions change |
The Map way records each number it has passed, with its index. For each number, it only checks whether its partner (target - number) has been passed already. Checking and recording in a Map take constant time on average, so the whole thing is O(n):
function twoSumMap(arr, target) {
const seen = new Map(); // number -> index
for (let i = 0; i < arr.length; i++) {
const pair = target - arr[i];
if (seen.has(pair)) return [seen.get(pair), i];
seen.set(arr[i], i);
}
return null;
}
console.log(twoSumMap([7, 1, 5, 3], 8)); // [0, 1]
Another pattern: checking a palindrome
Two pointers from both ends can also compare the items at their two positions, for example to check a palindrome: a word that reads the same forwards and backwards. str[left] in this code is the letter at index left:
function isPalindrome(str) {
let left = 0;
let right = str.length - 1;
while (left < right) {
if (str[left] !== str[right]) return false;
left++;
right--;
}
return true;
}
console.log(isPalindrome("level")); // true
console.log(isPalindrome("label")); // false
As soon as one pair of letters is different, the function returns false. Here both pointers always move together towards the middle. There are also two pointers that move in the same direction: one slow, one fast. They are used, for example, to remove repeated numbers (numbers that appear more than once) from a sorted array, without making a new array.
⚠️ Wrong pairs, or a number paired with itself
- The array isn't sorted. Finding a pair with two pointers is only right in a sorted array. In
[7, 1, 5], movingleftdoesn't always give a bigger number. left <= right. With<=, the loop keeps running when both pointers point at the same index. So a number can be paired with itself:twoSum([1, 3, 5], 10)gives[2, 2](5 + 5), though there's no pair. Use<.- Moving the wrong way. A sum that's too small needs a bigger number, so
left++, notright--.
TL;DR: Two pointer uses two variables that hold indexes (pointers), left at the start and right at the end of a sorted array. They find two numbers that add up to a target. Sum too small: left++. Too big: right--. A match: return [left, right], the positions of the two numbers. The pointers meet (left < right is no longer true): return null. Every step drops one number that can't be part of the answer, so it's O(n), not O(n²) like trying every pair. The same pattern checks a palindrome (a word that reads the same forwards and backwards) from both ends.
⚡ Both ends moving closer
Write:
function 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]; // a match: return the positions
if (sum < target) left++; // too small: take a bigger number
else right--; // too big: take a smaller number
}
return null; // the pointers met: no pair
}
Meaning: twoSum looks for two numbers in the sorted array arr that add up to target. It uses two pointers (variables that hold an index): left starts at index 0, right at the last index. When the sum matches the target, return the positions, not the numbers. Use left < right, not <=, so a number is never paired with itself.
⚡ Why moving is allowed
Guess first: in [1, 3, 5, 7, 11, 13, 17] with a target of 16, 1 + 17 = 18 is too big. Why can 17 be dropped right away (skipped with right--)?
The array is sorted, so 1 is the smallest number. 17 paired with even the smallest number is already too big, so 17 can't be part of the answer.
Meaning: Every step safely drops one number, so n numbers take at most n - 1 steps: O(n), not O(n²) like trying every pair. The condition: the array must be sorted.
⚡ Another pattern: checking a palindrome
Write:
function isPalindrome(str) {
let left = 0;
let right = str.length - 1;
while (left < right) {
if (str[left] !== str[right]) return false;
left++;
right--;
}
return true;
}
console.log(isPalindrome("level")); // true
Meaning: A palindrome is a word that reads the same forwards and backwards. isPalindrome compares the letters at left and right, then moves both pointers together towards the middle. One pair of different letters is enough to return false.