#142
Medium Algorithms Linked list cycle ii
Hash Table Linked List Two Pointers
57.3% acceptance
Jan 13, 2026
15072
1085
Given the head of a linked list, return the node where the cycle begins.
If there is no cycle, return null.
Solution
C++
Time O(n²)
Space O(1)
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) {
slow = head;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
return slow;
}
}
return nullptr;
}
};