Table of Contents
Problem Statement
Linked List Cycle II LeetCode Solution – 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 the 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.)
We are not allowed to modify the linked list.
Input: head = [3,2,0,-4], pos = 1 Output: tail connects to node index 1 Explanation: There is a cycle in the linked list, where tail connects to the second node.
Explanation
slow
moves 1 step at a time,fast
moves 2 steps at a time.- when
slow
andfast
meet each other, they must be on the cyclex
denotes the length of the linked list before starting the circley
denotes the distance from the start of the cycle to whereslow
andfast
metC
denotes the length of the cycle- when they meet, slow traveled
(x + y)
steps whilefast
traveled2 * (x + y)
steps, and the extra distance(x + y)
must be a multiple of the circle lengthC
- note that
x
,y
,C
are all lengths or the number of steps needed to move. head
,slow
,fast
are pointers.head
movesx
steps and arrives at the start of the cycle.
- note that
- so we have
x + y = N * C
, letslow
continue to travel fromy
and afterx
more steps,slow
will return to the start of the cycle. - At the same time, according to the definition of x,
head
will also reach the start of the cycle after movingx
steps. - so if
head
andslow
start to move at the same time, they will meet at the start of the cycle, that is the answer.
Code
Java Code for
public class Solution { public ListNode detectCycle(ListNode head) { ListNode slow = head, fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) break; } if (fast == null || fast.next == null) return null; while (head != slow) { head = head.next; slow = slow.next; } return head; } }
C++ Code for
class Solution { public: ListNode *detectCycle(ListNode *head) { ListNode *slow = head, *fast = head; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) break; } if (!(fast && fast->next)) return NULL; while (head != slow) { head = head->next; slow = slow->next; } return head; } };
Python Code for
class Solution(object): def detectCycle(self, head): slow = fast = head while fast and fast.next: slow, fast = slow.next, fast.next.next if slow == fast: break else: return None # if not (fast and fast.next): return None while head != slow: head, slow = head.next, slow.next return head
Complexity Analysis for Linked List Cycle II LeetCode Solution
Time Complexity
O(N) since slow ptr moves to every node.
Space Complexity
O(1) as we are using two constant iterators for the linked list (slow and fast)