Scanning & Windows
Two Pointers
⚔️
Picture this
Two armoured knights march from opposite ends of a long banquet table, closing in until they meet.
When you see it
Signal words
If the prompt uses any of these, this pattern should come to mind first.
sorted arraypair / triplettwo sumpalindromeremove duplicatesopposite ends
Ask yourself
- Sorted input, or can sorting help?
- Looking for a pair/triplet meeting a condition?
- Can one pass with converging pointers replace a nested loop?
Canonical template
let i = 0, j = a.length - 1;
while (i < j) {
const sum = a[i] + a[j];
if (sum === target) return [i, j];
if (sum < target) i++;
else j--;
}
Common pitfalls
Forgetting to skip duplicates in 3Sum-style problems.
Moving the wrong pointer for the condition.