142. Linked List Cycle II
Asked at 12Microsoft45Amazon44Bloomberg40Google36Meta22IBM35Paytm79American Express53ByteDance50Infosys39tcs27Oracle27
Problem
Return the node where the cycle in a linked list begins, or null if there is no cycle. Don't modify the list.
Example: 3→2→0→-4 with the tail pointing back to 2 → the node 2
Constraints: follow-up: O(1) extra memory.
After slow and fast meet, restart one pointer at head; moving both one step at a time, they meet at the cycle entrance. (Distance head→entry ≡ distance meet→entry mod cycle length.)
head -> a -> b -> [c] -> d -> e
^ |
+-----------+ x = head..c, meet inside; x ≡ meet..c
Complexity: O(n) time, O(1) space.
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast:
p = head
while p is not slow:
p, slow = p.next, slow.next
return p
return None
h = make_list([3, 2, 0, -4]); h.next.next.next.next = h.next
assert Solution().detectCycle(h) is h.next
assert Solution().detectCycle(make_list([1])) is None
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) {
ListNode p = head;
while (p != slow) { p = p.next; slow = slow.next; }
return p;
}
}
return null;
}
}
func detectCycle(head *ListNode) *ListNode {
slow, fast := head, head
for fast != nil && fast.Next != nil {
slow, fast = slow.Next, fast.Next.Next
if slow == fast { // the cycle start is as far from head as from the meeting point
p := head
for p != slow {
p, slow = p.Next, slow.Next
}
return p
}
}
return nil
}