7.10 Linked List Cycle II
7.10.1 Problem Metadata
- Platform: LeetCode
- Problem ID: 142
- Difficulty: Medium
- URL: https://leetcode.com/problems/linked-lc-list-cycle-ii/
- Tags:
- Techniques: Two Pointers, Linked List
7.10.3 Solution - Floyd’s Cycle Detection with Entry Point
7.10.3.1 Walkthrough
This problem extends Floyd’s cycle detection to find where the cycle starts. After detecting a cycle (when slow and fast meet), reset one pointer to head and move both pointers one step at a time. They will meet at the cycle’s entry point.
Mathematical proof: Let a be the distance from head to cycle start, and b be the distance from cycle start to meeting point. When they meet, slow traveled a + b steps, fast traveled 2(a + b) steps. The difference a + b equals the cycle length c. So a = c - b, meaning the distance from head to cycle start equals the distance from meeting point to cycle start (going forward in the cycle).
7.10.3.2 Analysis
- Time Complexity: O(n) - Two traversals at most
- Space Complexity: O(1) - Only pointer variables used
7.10.3.3 Implementation Steps
- Use Floyd’s algorithm to detect if a cycle exists and find the meeting point.
- If no cycle, return null.
- Reset one pointer (
ptr) to head, keepslowat meeting point. - Move both one step at a time until they meet - that’s the cycle entry.