04
Fast & Slow Pointers
Linked list cycles and finding the middle.
5 pages
- Pattern 04: Fast & Slow Pointers (Floyd's Cycle Detection)Pattern guide
One skeleton, three questions: is there a cycle, where does it start, what's the middle.
- LC 876Middle of the Linked List (LC 876)Easy
Move fast two steps per iteration and slow one step; when fast reaches the end, slow lands on the middle (second middle when length is even).
- LC 202Happy Number (LC 202)Easy
Repeatedly map n to the sum of squares of its digits; a happy number eventually reaches 1; otherwise the sequence cycles — detect the cycle with a hash set…
- LC 234Palindrome Linked List (LC 234)Easy
For O(1) extra space, find the middle with fast/slow, reverse the second half, then compare the first half with the reversed half node by node.
- LC 83Remove Duplicates from Sorted List (LC 83)Easy
Because the list is sorted, duplicates appear next to each other — skip next when current.val == current.next.val without a hash set.