Preview — Pro guide
You are seeing a portion of this guide. Sign in and upgrade to unlock the full article, quizzes, and interview answers.
Two Pointers: Converging, Fast/Slow, and Floyd's Cycle Detection
Three distinct two-pointer variants with precise invariants, proven correctness, and production-quality implementations. Covers converging pointers for sorted arrays, fast/slow for duplicates and linked list middle, and Floyd's cycle detection with the phase 2 math that most candidates get wrong.
Three Variants, Three Invariants
Two pointers is not a single pattern but a family of three distinct techniques, each with a different invariant and a different class of problems. Conflating them — or knowing only one — is a common interview failure mode.
Converging (opposite ends): left starts at index 0, right starts at the last index. They move toward each other. Invariant: left < right. The mechanism: you can skip large portions of the search space because the array is sorted — if arr[left] + arr[right] > target, moving right left is safe because any element to the right of right would make the sum even larger. Classic problems: 2Sum on sorted array, container with most water, trapping rain water, 3Sum (fix one, converge two).
Same-direction (fast/slow): Both pointers start at the beginning and move rightward, but at different speeds or triggered by different conditions. The invariant: everything to the left of the slow pointer satisfies some property (e.g., is a unique element), and the fast pointer scans ahead to find the next element that should be placed at slow. Classic problems: remove duplicates from sorted array, move zeros, remove element in-place.
Floyd's cycle detection (hare/tortoise): One pointer moves one step per iteration, the other moves two. Used exclusively on linked list structures where you cannot compute length or use indexing. Classic problems: detect cycle in linked list, find cycle start, find middle of linked list, find duplicate number in array (treats array as implicit linked list).
What Interviewers Are Testing
Interviewers test two things beyond the mechanics: (1) Can you prove why the converging approach is safe — why moving the smaller-max pointer in trapping rain water gives the correct answer, not just a greedy heuristic? (2) Can you explain Floyd's phase 2 math — why resetting one pointer to the head and advancing both at the same speed finds the cycle entry? Candidates who say 'I know it works from LeetCode' fail this probe. Candidates who explain the phase 2 math (distance from head to cycle start = distance from meeting point to cycle start mod cycle length) pass.