Linked List Cycle II
Medium
Linked ListTwo PointersCycle Detection
Problem
Given the head of a linked list, return the node where the cycle begins, or null if there is no cycle.
Example 1
Input: [3,2,0,-4], cycle at index 1
Output: node with val 2
Example 2
Input: [1,2], cycle at index 0
Output: node with val 1
Example 3
Input: [1], no cycle
Output: null
Constraints
- 0 ≤ length ≤ 10⁴
Approach — Two Pointers
This is a Two Pointers problem. The idea: walk two indices through the data together (or toward each other), turning an O(n²) pair search into one linear pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(1) extra space.
Solution code
Python
class Solution:
def detectCycle(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
p = head
while p is not slow:
p = p.next
slow = slow.next
return p
return None
Java
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) {
slow = head;
while (slow != fast) { slow = slow.next; fast = fast.next; }
return slow;
}
}
return null;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Linked List Cycle II interactively → ← All solutions