KatInterview

142. Linked List Cycle II

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the starting node of a cycle in a linked list. If no cycle exists, we should return null. The key challenge is to solve this using O(1) constant memory, which rules out the straightforward approach of using a hash set to store visited nodes.

Solution

Linked List Cycle II in Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        # Handle edge cases: empty list or single-node list
        if not head or not head.next:
            return None

        slow = head
        fast = head

        # Phase 1: Detect if a cycle exists using Floyd's Tortoise and Hare algorithm
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                # Cycle detected. Now find the start of the cycle.
                
                # Phase 2: Find the cycle's start node
                ptr1 = head
                ptr2 = slow # or fast, they are at the same meeting point

                # Move both pointers one step at a time. They will meet at the cycle's start.
                while ptr1 != ptr2:
                    ptr1 = ptr1.next
                    ptr2 = ptr2.next
                
                return ptr1 # Return the start of the cycle

        # If the loop finishes, it means fast reached the end, so no cycle.
        return None

Linked List Cycle II in Java

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        // Handle edge cases: empty list or single-node list
        if (head == null || head.next == null) {
            return null;
        }

        ListNode slow = head;
        ListNode fast = head;

        // Phase 1: Detect if a cycle exists
        // Use Floyd's Tortoise and Hare algorithm
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;

            if (slow == fast) {
                // Cycle detected. Now find the start of the cycle.

                // Phase 2: Find the cycle's start node
                ListNode ptr1 = head;
                ListNode ptr2 = slow; // or fast, as they are at the same meeting point

                // Move both pointers one step at a time.
                // They will meet at the start of the cycle.
                while (ptr1 != ptr2) {
                    ptr1 = ptr1.next;
                    ptr2 = ptr2.next;
                }
                return ptr1; // Return the start of the cycle
            }
        }

        // If the loop finishes, it means fast reached the end, so no cycle.
        return null;
    }
}

Linked List Cycle II in C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        // Handle edge cases: empty list or single-node list
        if (head == nullptr || head->next == nullptr) {
            return nullptr;
        }

        ListNode *slow = head;
        ListNode *fast = head;

        // Phase 1: Detect if a cycle exists
        // Use Floyd's Tortoise and Hare algorithm
        while (fast != nullptr && fast->next != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) {
                // Cycle detected. Now find the start of the cycle.
                
                // Phase 2: Find the cycle's start node
                ListNode *ptr1 = head;
                ListNode *ptr2 = slow; // or fast, as they are at the same meeting point

                // Move both pointers one step at a time.
                // They will meet at the start of the cycle.
                while (ptr1 != ptr2) {
                    ptr1 = ptr1->next;
                    ptr2 = ptr2->next;
                }
                return ptr1; // Return the start of the cycle
            }
        }

        // If the loop finishes, it means fast reached the end, so no cycle.
        return nullptr;
    }
};

Linked List Cycle II in TypeScript

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function detectCycle(head: ListNode | null): ListNode | null {
    // Handle edge cases: empty list or single-node list
    if (head === null || head.next === null) {
        return null;
    }

    let slow: ListNode | null = head;
    let fast: ListNode | null = head;

    // Phase 1: Detect if a cycle exists
    // Use Floyd's Tortoise and Hare algorithm
    while (fast !== null && fast.next !== null) {
        slow = slow!.next;
        fast = fast.next.next;

        if (slow === fast) {
            // Cycle detected. Now find the start of the cycle.

            // Phase 2: Find the cycle's start node
            let ptr1: ListNode | null = head;
            let ptr2: ListNode | null = slow;

            // Move both pointers one step at a time.
            // They will meet at the start of the cycle.
            while (ptr1 !== ptr2) {
                ptr1 = ptr1!.next;
                ptr2 = ptr2!.next;
            }
            return ptr1; // Return the start of the cycle
        }
    }

    // If the loop finishes, it means fast reached the end, so no cycle.
    return null;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.