Learn how the two pointers pattern searches sorted arrays, finds pairs that meet a condition, and replaces nested loops with linear-time scans.
The two pointers pattern uses two variables to track positions in a linear structure such as an array, string, or linked list. The pointers move according to a condition until they meet, cross, or reach the end.
In code, a pointer is usually just a number that stores an index:
The pointers can move toward each other from opposite ends, move in the same direction, or move from the end toward the beginning. The important idea is that each pointer moves forward through the data instead of restarting a search for every item.
Core idea
Use two references to narrow the search space. When the input is sorted or has a useful left-to-right structure, pointer movement can replace nested loops and reduce a quadratic scan to linear time.
Two pointers are especially useful when:
For a target-sum pair, sorted values justify eliminating an endpoint. A palindrome uses a different property: its first and last characters must match, regardless of alphabetic order.
Write a function called sumZero that accepts a sorted array of integers. Return two values from distinct positions whose sum is zero. If no pair exists, return undefined in JavaScript or None in Python.
sumZero([-4, -3, -2, -1, 0, 1, 2, 5]) → [-2, 2]
sumZero([-4, -3, -2, 0, 1, 5]) → undefinedThe array must be sorted from the smallest value to the largest value. That ordering lets us decide which pointer to move after each comparison.
The direct solution checks every possible pair with nested loops:
function sumZeroNaive(numbers) {
for (let i = 0; i < numbers.length; i++) {
for (let j = i + 1; j < numbers.length; j++) {
if (numbers[i] + numbers[j] === 0) {
return [numbers[i], numbers[j]];
}
}
}
return undefined;
}For each value, the inner loop scans the remaining values. With n items and no matching pair, it checks n(n − 1)/2 pairs, giving O(n²) time.
Place one pointer at the smallest value and one at the largest value:
left = 0
right = numbers.length - 1Then compare the values at those positions:
| Sum | Meaning | Move |
|---|---|---|
0 | The pair matches | Return both values |
Greater than 0 | The sum is too large | Move right left to a smaller value |
Less than 0 | The sum is too small | Move left right to a larger value |
If the sum is too large, even the smallest remaining left value makes the right value too large. Every other remaining partner is at least as large, so discard that right endpoint. If the sum is too small, even the largest remaining right value falls short with the left value, so discard that left endpoint.
function sumZero(numbers) {
let left = 0;
let right = numbers.length - 1;
while (left < right) {
const sum = numbers[left] + numbers[right];
if (sum === 0) {
return [numbers[left], numbers[right]];
}
if (sum > 0) {
right--;
} else {
left++;
}
}
return undefined;
}Start at the two ends of the sorted array. Before advancing, use the sum of the highlighted values to predict which pointer moves.
Enter up to 64 integers in brackets, smallest to largest. Equal values are allowed. Use [] for an empty array.
Step 1 of 4. Even with -4, the smallest remaining partner, 5 makes the sum too large. Move R one place left.
left value | right value | Sum | Decision |
|---|---|---|---|
-4 | 5 | 1 | Too large, move right left |
-4 | 2 | -2 | Too small, move left right |
-3 | 2 | -1 | Too small, move left right |
-2 | 2 | 0 | Return [-2, 2] |
One endpoint moves on every unsuccessful comparison, reducing the distance between the pointers by one. A position can be compared several times while the opposite pointer moves, but there are at most n − 1 comparisons for a nonempty array. Its time complexity is O(n) and its extra space complexity is O(1).
The pointers do not always start at opposite ends.
To check whether a string is a palindrome, compare the first and last characters, then move inward:
function isPalindrome(text) {
let left = 0;
let right = text.length - 1;
while (left < right) {
if (text[left] !== text[right]) return false;
left++;
right--;
}
return true;
}This scan also takes O(n) time and O(1) extra space when the input can be indexed directly.
| Approach | Main method | Typical time | Extra space |
|---|---|---|---|
| Nested loops | Compare each item with many other items | O(n²) | O(1) |
| Two pointers | Move two positions based on a condition | O(n) | O(1) |
The linear solution depends on a property such as sorted order. Without that property, moving a pointer may discard a valid pair, so the optimization is not automatically safe.
Pattern checklist
Before using two pointers, ask: What does the order of the input tell me? Which pointer can move without skipping a valid answer? When should the pointers stop? Answering these questions makes the loop condition and pointer movement precise.
O(n²) nested loops with fast O(n) single passes.O(1) extra memory because it only tracks two index numbers without creating new arrays or maps.Apply the opposite-end scan to a sorted array in Two Sum II.