Algorithm-Day26-Linked-List-Cycle-II-lc142
π§© Problem Description
Given the head
of a linked list, return the node where the cycle begins.
If there is no cycle, return null
.
You must not modify the list.
Example:
1 | Input: head = [3,2,0,-4], pos = 1 (tail connects to node at index 1) |
π‘ Step 1: Detect Cycle Using Two Pointers
Use Floydβs Cycle Detection (Tortoise and Hare):
slow
moves one step,fast
moves two steps.- If they ever meet, thereβs a cycle.
- β Already used in lc-141
π‘ Step 2: Find Entry Point of the Cycle
β¨ Key Insight
Once slow
and fast
meet:
- Start a new pointer
ptr1
from head. - Start a second pointer
ptr2
from whereslow
andfast
met. - Move both one step at a time.
- They will meet at the cycle entry.
π Why it works:
Let:
L1
= distance from head to cycle startL2
= distance from cycle start to meeting pointC
= length of the cycle
Then:2(L1 + L2) = L1 + L2 + kC βΉ L1 = kC - L2
So moving L1
from head and L2
from meeting point leads to cycle start.
π’ Java Code
1 | public class Solution { |
β± Time and Space Complexity
- Time Complexity: O(n)
- Space Complexity: O(1)
βοΈ Summary
- First detect cycle with two pointers.
- Then find the node where cycle begins by moving a new pointer from
head
. - No extra memory needed β all in-place.
This is one of the most elegant applications of two-pointer technique in linked lists. Master it!