Algo-Sim › Linked Lists
Linked List Cycle II
Medium · Linked Lists · step through it in Java, Python and C++ on your own input
Find the node where the cycle begins: meet with fast and slow pointers, then walk from the head and the meeting point together.
Problem
Given the head of a linked list, return the node where its cycle begins, or null if there is no cycle. Do not modify the list.
Constraints
- 0 ≤ number of nodes ≤ 10⁴
- -10⁵ ≤ Node.val ≤ 10⁵
- pos is −1 or a valid index
- Follow-up: O(1) memory
Edge cases to test
- No cycle: return null
- The cycle starts at the head
- A self-loop at the tail
Follow-up questions
- Why does restarting from the head work?
- If the tail before the cycle is a and they meet b into the cycle of length c, then a ≡ c − b (mod c), so both pointers reach the start together.
- How do you get the cycle length?
- From the meeting point, step until you are back: c steps.
Solution
Java
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) {
ListNode entry = head;
while (entry != slow) {
entry = entry.next;
slow = slow.next;
}
return entry;
}
}
return null;
}Python
def detect_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
entry = head
while entry is not slow:
entry = entry.next
slow = slow.next
return entry
return NoneC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
ListNode *entry = head;
while (entry != slow) {
entry = entry->next;
slow = slow->next;
}
return entry;
}
}
return nullptr;
}
};
More Linked Lists problems
- Reverse Linked List (Easy)
- Reverse Linked List (Recursive) (Easy)
- Merge Two Sorted Lists (Easy)
- Middle of the Linked List (Easy)
- Palindrome Linked List (Easy)
- Linked List Cycle (Easy)
- Intersection of Two Linked Lists (Easy)
- Find the Duplicate Number (Medium)
- Remove Nth Node From End of List (Medium)
- Reorder List (Medium)
- Sort List (Medium)
- Add Two Numbers (Medium)
- Copy List with Random Pointer (Medium)
- Reverse Nodes in k-Group (Hard)