Algo-Sim › Linked Lists

Linked List Cycle II

Medium · Linked Lists · step through it in Java, Python and C++ on your own input

Find the node where the cycle begins: meet with fast and slow pointers, then walk from the head and the meeting point together.

Problem

Given the head of a linked list, return the node where its cycle begins, or null if there is no cycle. Do not modify the list.

Constraints

Edge cases to test

Follow-up questions

Why does restarting from the head work?
If the tail before the cycle is a and they meet b into the cycle of length c, then a ≡ c − b (mod c), so both pointers reach the start together.
How do you get the cycle length?
From the meeting point, step until you are back: c steps.

Solution

Java

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 entry = head;
            while (entry != slow) {
                entry = entry.next;
                slow = slow.next;
            }
            return entry;
        }
    }
    return null;
}

Python

def detect_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            entry = head
            while entry is not slow:
                entry = entry.next
                slow = slow.next
            return entry
    return None

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *slow = head, *fast = head;
        while (fast != nullptr && fast->next != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) {
                ListNode *entry = head;
                while (entry != slow) {
                    entry = entry->next;
                    slow = slow->next;
                }
                return entry;
            }
        }
        return nullptr;
    }
};

More Linked Lists problems