Linked List Cycle II
Find the node where a linked list cycle begins in O(n) time and O(1) space using two-phase pointer reset.
01The problem
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.
Do not modify the linked list. Can you solve it using O(1) memory?
| Input | Output | Why |
|---|---|---|
[3, 2, 0, -4], pos = 1 | Node(2) | Cycle loops back to index 1 (node with value 2) |
[1, 2], pos = 0 | Node(1) | Cycle loops back to index 0 (node with value 1) |
[1], pos = -1 | null | No cycle; returns null |
Constraints: 0 to 10,000 nodes, node values between -100,000 and 100,000, pos is -1 or a valid index.
Loading the rest of the lesson…