Module 1 · Lesson 3 · ~20 min
Two pointers is the pattern that turns "compare every pair" (O(n²)) into "make one sweep" (O(n)). Master it and an entire family of interview problems collapses into a five-line answer.
Imagine 20 people lined up by height, shortest on the left, tallest on the right. You're asked: "Find a pair whose heights sum to exactly 6 feet."
The brute force: for every person, ask every other person their height. 20 × 20 = 400 questions.
The smart move: you station Reader A at the shortest and Reader B at the tallest. Add their heights. Too high? Reader B walks left (shorter target). Too low? Reader A walks right (taller target). They walk toward each other until they meet. At most 20 questions.
Both pointers start at opposite ends and walk toward each other. Used when the array is sorted and you're looking for a pair satisfying some sum/difference condition.
def two_sum_sorted(nums, target):
i, j = 0, len(nums) - 1
while i < j:
s = nums[i] + nums[j]
if s == target: return [i, j]
if s < target: i += 1
else: j -= 1
return []
# O(n) time, O(1) space — assuming the input is sorted.
function twoSumSorted(nums, target) {
let i = 0, j = nums.length - 1;
while (i < j) {
const s = nums[i] + nums[j];
if (s === target) return [i, j];
if (s < target) i++;
else j--;
}
return [];
}
// O(n) time, O(1) space — assuming the input is sorted.
function twoSumSorted(nums: number[], target: number): number[] {
let i = 0, j = nums.length - 1;
while (i < j) {
const s = nums[i] + nums[j];
if (s === target) return [i, j];
if (s < target) i++;
else j--;
}
return [];
}
// O(n) time, O(1) space — assuming the input is sorted.
Both pointers start at the left and one moves faster than the other. Used for in-place partitioning, removing duplicates, cycle detection, and the special case of moving zeros to the end.
# Remove duplicates from a sorted array, in place. Return new length.
def dedupe(nums):
if not nums: return 0
write = 1
for read in range(1, len(nums)):
if nums[read] != nums[read - 1]:
nums[write] = nums[read]
write += 1
return write
# read pointer scans every element once; write pointer trails behind
// Remove duplicates from a sorted array, in place. Return new length.
function dedupe(nums) {
if (!nums.length) return 0;
let write = 1;
for (let read = 1; read < nums.length; read++) {
if (nums[read] !== nums[read - 1]) {
nums[write] = nums[read];
write++;
}
}
return write;
}
// read pointer scans every element once; write pointer trails behind
// Remove duplicates from a sorted array, in place. Return new length.
function dedupe(nums: number[]): number {
if (!nums.length) return 0;
let write = 1;
for (let read = 1; read < nums.length; read++) {
if (nums[read] !== nums[read - 1]) {
nums[write] = nums[read];
write++;
}
}
return write;
}
// read pointer scans every element once; write pointer trails behind
| If you see… | Reach for… | Big-O |
|---|---|---|
| "Two-sum on a sorted array" | Converging pointers | O(n) |
| "Three-sum / four-sum" | Sort, then for each i, two-pointer the rest | O(n²) / O(n³) |
| "Container with most water" / "Trapping rainwater" | Converging pointers, height-based | O(n) |
| "In-place dedupe / partition / move zeros" | Slow / fast pointers | O(n) |
| "Detect cycle in linked list" | Floyd's tortoise & hare | O(n) |
| "Reverse / palindrome check" | Converging pointers | O(n) |
Two pointers walking inward on a sorted array, looking for sum = 12.
"The brute force is O(n²) — every pair. Since the array is sorted, I can use two pointers — left at the start, right at the end. If the sum is too low, advance left. If too high, retreat right. They meet in the middle in O(n) time, O(1) space."
That sentence — said in 12 seconds before you write a single character of code — is the entire optimization narrative. Practice it.
def is_palindrome(s):
i, j = 0, len(s) - 1
while i < j:
while i < j and not s[i].isalnum(): i += 1
while i < j and not s[j].isalnum(): j -= 1
if s[i].lower() != s[j].lower(): return False
i += 1; j -= 1
return True
function isPalindrome(s) {
const isAN = c => /[a-zA-Z0-9]/.test(c);
let i = 0, j = s.length - 1;
while (i < j) {
while (i < j && !isAN(s[i])) i++;
while (i < j && !isAN(s[j])) j--;
if (s[i].toLowerCase() !== s[j].toLowerCase()) return false;
i++; j--;
}
return true;
}
function isPalindrome(s: string): boolean {
const isAN = (c: string) => /[a-zA-Z0-9]/.test(c);
let i = 0, j = s.length - 1;
while (i < j) {
while (i < j && !isAN(s[i])) i++;
while (i < j && !isAN(s[j])) j--;
if (s[i].toLowerCase() !== s[j].toLowerCase()) return false;
i++; j--;
}
return true;
}