7.9 Linked List Cycle
7.9.1 Problem Metadata
- Platform: LeetCode
- Problem ID: 141
- Difficulty: Easy
- URL: https://leetcode.com/problems/linked-lc-list-cycle/
- Tags: Grind 75, Blind 75, NeetCode 150
- Techniques: Two Pointers, Linked List
7.9.3 Solution - Floyd’s Cycle Detection
7.9.3.1 Walkthrough
Floyd’s algorithm uses two pointers moving at different speeds. The slow pointer advances one node at a time while the fast pointer advances two nodes. If there’s a cycle, the fast pointer will eventually catch up to the slow pointer from behind (they will meet). If there’s no cycle, the fast pointer will reach the end (null).
Why they must meet if a cycle exists: Once both pointers enter the cycle, the fast pointer closes the gap by 1 node per iteration. Since the gap decreases by exactly 1 each step, they will eventually meet.
7.9.3.2 Analysis
- Time Complexity: O(n) - In the worst case, we traverse the list twice (once to enter the cycle, once to meet)
- Space Complexity: O(1) - Only two pointers used