Quick Overview
A nested loop tests every pair in O(N^2). On sorted data, moving two pointers inward from both ends rules out half the remaining candidates at each step and settles it in one O(N) pass.
The Two Pointers Pattern uses two index pointers that start at opposite ends of a sequence (left = 0 and right = arr.length - 1) and move toward each other until they meet.
Instead of checking all pairs with nested loops in O(N^2) quadratic time, two pointers reduce the search space to a single linear pass in O(N) time and O(1) space.
Given an array sorted in ascending order, find two numbers that sum to a given target:
function twoSumSorted(numbers, target) {
let left = 0;
let right = numbers.length - 1;
while (left < right) {
const currentSum = numbers[left] + numbers[right];
if (currentSum === target) {
return [left, right]; // Found exact pair!
} else if (currentSum < target) {
left++; // Sum is too small, move left pointer rightward to increase sum
} else {
right--; // Sum is too large, move right pointer leftward to decrease sum
}
}
return []; // No pair found
}
// Example Execution
console.log(twoSumSorted([2, 7, 11, 15], 9)); // Output: [0, 1]
console.log(twoSumSorted([1, 3, 4, 8, 10], 12)); // Output: [2, 3] (4 + 8)
Array: [ 2 , 7 , 11 , 15 ] Target: 9
▲ ▲
left right Sum: 2 + 15 = 17 (> 9) -> right--
Array: [ 2 , 7 , 11 , 15 ]
▲ ▲
left right Sum: 2 + 11 = 13 (> 9) -> right--
Array: [ 2 , 7 , 11 , 15 ]
▲ ▲
left right Sum: 2 + 7 = 9 (Match!) -> Return [0, 1]
O(N log N) or you should use a Hash Map in O(N).while (left <= right) for pair sum problems can cause an element to be added to itself if left === right. Use left < right for distinct pairs.Use converging pointers on sorted arrays and palindromes. Next, let's explore Fast and Slow Pointers for Cycle Detection!
Big O describes how work grows, not how long it takes. An O(N^2) algorithm on 1,000 items does a million steps; the same work at O(N log N) does about 10,000.
A dynamic array doubles rather than growing by one, so the expensive copy lands on the 1st, 2nd, 4th and 8th push. Averaged across every push, that is O(1) amortised.
Two pointers moving at different speeds must eventually meet inside a loop, the way a faster runner laps a slower one. That detects a cycle in O(N) time and O(1) space, with no visited set.