DSA AnimatorDSA animations
Linked List Cycle II LC #142 Medium Fast & Slow Pointers
Problem

Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null. Internally, pos is the index the tail's next points to (-1 means no cycle). Do not modify the list, and use O(1) extra memory.

Example 1
Input: head = [3,2,0,-4], pos = 1
Output: node at index 1
Example 2
Input: head = [1,2], pos = 0
Output: node at index 0
Example 3
Input: head = [1], pos = -1
Output: null (no cycle)
Constraints: 0 โ‰ค nodes โ‰ค 10โด  |  โˆ’10โต โ‰ค Node.val โ‰ค 10โต  |  pos is โˆ’1 or a valid index
๐Ÿ”— Linked list
โ‘  ๐Ÿข๐Ÿ‡ find a meeting pointโ‘ก walk both 1 step โ†’ cycle start
๐Ÿงฎ Why phase 2 works
๐Ÿข slow (1 step)๐Ÿ‡ fast (2 steps)๐Ÿ’ฅ meeting pointโญ cycle start a: head โ†’ start b: start โ†’ meet c: meet โ†’ start
Variables
๐Ÿข slow
โ€”
๐Ÿ‡ fast
โ€”
steps
0
phase
โ€”
๐Ÿ’ก Step Logic
Press โ–ถ Play or Next to begin.
โœ“
Ready
0 / 0
Pick an example and press Play.
Algorithm
1
Start ๐Ÿข and ๐Ÿ‡ at head
2
Move ๐Ÿข 1 step and ๐Ÿ‡ 2 steps until they meet ๐Ÿ’ฅ, or ๐Ÿ‡ hits null (no cycle)
3
Put ๐Ÿข back at head; keep ๐Ÿ‡ at the meeting point
4
Move both 1 step at a time until they meet
5
That node is the cycle start โญ โ€” return it
Time
O(n)
Space
O(1)
๐Ÿง  The math in one line

When they meet, ๐Ÿข has walked a + b and ๐Ÿ‡ has walked 2(a + b), which is also a + b + kยทL (it lapped the loop k times). So a + b = kยทL, i.e. a = kยทL โˆ’ b = (k โˆ’ 1)ยทL + c. Walking a steps from the meeting point lands on the start. That's exactly what walking a steps from head does.

โš ๏ธ Edge cases

Empty list or one node without a loop โ†’ return null. Cycle starts at head (pos = 0) โ†’ they meet, and after the reset both are already on the answer. Self-loop at the tail works the same way. A HashSet solution is simpler but uses O(n) memory; interviewers expect this O(1) version.