ππ Two Pointers
One-line summary: Use two indices that move toward each other (or in the same direction) to eliminate the O(nΒ²) nested loop β achieving O(n) on sorted data.
Conceptβ
Two pointers maintains two indices β left and right β and moves them strategically:
- Opposite-direction (converging): both ends converge inward β sorted array, palindrome, container problems.
- Same-direction (fast/slow): both move forward, one faster β remove duplicates, cycle detection, is-subsequence.
Prerequisite: sorted array (for opposite-direction), or logical ordering for same-direction.
Diagramβ
Sorted: [1, 2, 3, 4, 6] target=6
L R
Step 1: 1+6=7 > 6 β R--
Step 2: 1+4=5 < 6 β L++
Step 3: 2+4=6 β
Time & Space Complexityβ
| Variant | Time | Space |
|---|---|---|
| Two Sum Sorted | O(n) | O(1) |
| Remove duplicates / Move Zeroes | O(n) | O(1) |
| Merge sorted arrays | O(m+n) | O(1) |
| Is Subsequence | O(n) | O(1) |
| Trapping Rain Water | O(n) | O(1) |
Common Patternsβ
Pattern 1 β Opposite Direction (Two Sum Sorted)β
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];
if (sum < target) left++;
else right--;
}
return [];
}
Pattern 2 β Same Direction (Move Zeroes)β
function moveZeroes(nums) {
let insertPos = 0;
for (let i = 0; i < nums.length; i++)
if (nums[i] !== 0) nums[insertPos++] = nums[i];
while (insertPos < nums.length) nums[insertPos++] = 0;
}
Pattern 3 β Fast/Slow (Is Subsequence)β
function isSubsequence(s, t) {
let i = 0, j = 0;
while (i < s.length && j < t.length) {
if (s[i] === t[j]) i++;
j++;
}
return i === s.length;
}
Pattern 4 β Fast/Slow (Cycle Detection in Linked List)β
function hasCycle(head) {
let slow = head, fast = head;
while (fast && fast.next) {
slow = slow.next; fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}
When to Useβ
- Sorted arrays where you need to find pairs or triplets
- Problems requiring partitioning or rearranging elements
- Optimising brute-force O(nΒ²) solutions to O(n)
- Palindrome checking in arrays/strings
- Cycle detection in linked lists (fast/slow variant)
Pitfallsβ
- Forgetting to sort the array first (opposite-direction only works on sorted input)
- Moving both pointers simultaneously instead of one at a time
- Off-by-one: use
left < rightnotleft <= rightfor converging pointers
Practice Problemsβ
Related Topicsβ
- Sliding Window β same-direction two pointers with a window constraint
- Binary Search β both reduce search space
- Sorting β prerequisite for opposite-direction
- Linked List β fast/slow pointer variant
β Back to Home Β· Β© sparshjaswal