Two Pointers (opposite ends)
Start one pointer at each end. Compare the current value against the target and move the pointer that can only improve the result.
Two PointersO(n) after sortingNew34 problems
18
mastery
Trigger phrases
If a problem statement sounds like one of these, try this pattern first.
sorted array
pair or triplet summing to target
container / area between two lines
palindrome check
The template
Get this into muscle memory, then adapt the condition per problem.
let l = 0, r = n - 1;
while (l < r) {
const cur = a[l] + a[r];
if (cur === target) return [l, r];
cur < target ? l++ : r--;
} Watch Two PointersIf you are stuck
The generic hint ladder for this pattern, in order.
- 1Does sorting lose information you need? Usually not when only values matter.
- 2From the ends, one move increases the sum and the other decreases it.
- 3Skip duplicates after recording an answer to avoid repeats.
Drill it
Every problem in the bank that uses this pattern.
0 / 34 solved