Linked List Cycle II

Pattern: Fast and slow pointers

medium

First find a meeting point with slow and fast pointers. Then move one pointer back to the head and walk both one step at a time. They meet exactly at the node where the cycle starts.

The problem

Given the head of a linked list, return the node where its cycle begins, or null if there is no cycle. Do not change the list. For example, 3 → 2 → 0 → -4 with the last node pointing back to 2 returns the node 2. Try to use O(1) extra memory.

The function name detectCycle matches LeetCode. Use the link above for the exact statement and limits. This guide's tests print the index of the returned node (-1 for null). The GFG link asks the same question.

Think first

  • When slow and fast meet, how far has each walked?
  • Let the cycle start L steps from the head. How far is the meeting point from the cycle start, going forwards?
  • What happens if one pointer walks L steps from the head and another walks L steps from the meeting point?

Hints

    Brute force, and why it fails

    A hash set of visited nodes returns the first node seen twice: O(n) time and O(n) memory. Floyd's two phases use O(1).

    The key insight

    The meeting point is exactly as far from the cycle start as the head is, measured around the loop. That bit of arithmetic turns "where does it start" into "where do two walkers meet".

    Dry run

    30 
    21 
    02 
    -43slow, fast

    The list is 3 → 2 → 0 → -4, and -4 points back to 2 (index 1). As in Linked List Cycle, slow and fast meet on -4.

    Step 1 of 4

    The plan

    slow = fast = head
    while fast and fast.next:
        slow = slow.next; fast = fast.next.next
        if slow == fast:
            a = head
            while a != slow: a = a.next; slow = slow.next
            return a
    return null
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Both phases walk at most a few times the length of the list.

    Edge cases

    • No cycle: null.
    • The cycle starts at the head: the second phase ends at once.
    • A one-node self-loop: that node.
    I've built my logic, show the code

    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) {                 // they met inside the loop
                    ListNode a = head;
                    while (a != slow) { a = a.next; slow = slow.next; }   // equal distances to the loop start
                    return a;
                }
            }
            return null;
        }
    }

    C++

    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) {                 // they met inside the loop
                    ListNode* a = head;
                    while (a != slow) { a = a->next; slow = slow->next; }   // equal distances to the loop start
                    return a;
                }
            }
            return NULL;
        }
    };

    Python

    from lib import ListNode
    
    class Solution:
        def detectCycle(self, head: ListNode) -> ListNode:
            slow = fast = head
            while fast is not None and fast.next is not None:
                slow, fast = slow.next, fast.next.next
                if slow is fast:                    # they met inside the loop
                    a = head
                    while a is not slow:            # equal distances to the loop start
                        a, slow = a.next, slow.next
                    return a
            return None

    Common mistakes

    • Returning the meeting point, which is usually not the start.
    • Moving the second phase at speed 2.
    • Marking visited nodes by changing values, which the question forbids.

    Similar problems