Coding patterns reels
When you see…
Sorted array or string · Find a pair or triplet with a target sum · Reverse, partition or remove in place · Palindrome checks
The idea
Put one pointer at each end. Compare, then move the pointer that can only improve the answer. Each step discards a whole row of possibilities, so you visit each element once.
Worked: 3Sum
Return all unique triplets in nums that sum to zero. Sort the array. Fix one number, then run two pointers on the rest for the negated value. Skip duplicates at every level so triplets stay unique.
Practise next
Valid Palindrome (Easy): Skip non-alphanumerics from both ends. Container With Most Water (Medium): Always move the shorter wall. Trapping Rain Water (Hard): Track left max and right max; move the smaller side.
Traps
Forgetting to sort first. Infinite loop when neither pointer moves. Duplicate answers without skip logic.
3Sum
Return all unique triplets in nums that sum to zero.
function threeSum(nums: number[]): number[][] {nums.sort((a, b) => a - b);const out: number[][] = [];for (let i = 0; i < nums.length - 2; i++) {if (i > 0 && nums[i] === nums[i - 1]) continue;let lo = i + 1, hi = nums.length - 1;while (lo < hi) {const s = nums[i] + nums[lo] + nums[hi];if (s < 0) lo++;else if (s > 0) hi--;else {out.push([nums[i], nums[lo], nums[hi]]);lo++;while (lo < hi && nums[lo] === nums[lo - 1]) lo++;}}}return out;}
Pair with target sum (sorted)
The reusable shape behind every two pointers problem. Memorise it, then adapt the twist.
function pairSum(nums: number[], target: number): [number, number] | null {let lo = 0, hi = nums.length - 1;while (lo < hi) {const s = nums[lo] + nums[hi];if (s === target) return [lo, hi];if (s < target) lo++;else hi--;}return null;}