Here’s the question link on Leetcode 142. Linked List Cycle II:
https://leetcode.com/problems/linked-list-cycle-ii/description
Contents
Brute Force – Using a Hash Set
We can store every visited node in an unordered_set.
While traversing the list:
- If we encounter a node we’ve already visited, that’s where the cycle begins.
- Otherwise, store the node and move forward.
- If we reach
NULL, there’s no cycle.
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
unordered_set<ListNode*> visited;
ListNode* curr = head;
while(curr != NULL) {
if(visited.find(curr) != visited.end()) {
return curr;
}
visited.insert(curr);
curr = curr->next;
}
return NULL;
}
};
Optimal – Floyd’s Cycle Detection (Slow and Fast Pointers)
We can solve this using two pointers without any extra space.
First, we’ll use Floyd’s Cycle Detection:
slowmoves one step at a time.fastmoves two steps at a time.- If they meet, a cycle exists.
But how do we find where the cycle starts?
Here’s the trick: After they meet, move slow back to the head. Keep fast at the meeting point. Now move both pointers one step at a time.
They will meet exactly at the starting node of the cycle.
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
// Detect the cycle
while(fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if(slow == fast) {
break;
}
}
// No cycle exists
if(fast == NULL || fast->next == NULL) {
return NULL;
}
// Find the starting node
slow = head;
while(slow != fast) {
slow = slow->next;
fast = fast->next;
}
return slow;
}
};