algoadvance

Leetcode 142. Linked List Cycle II

Problem Statement

Given a linked list, return the node where the cycle begins. If there is no cycle, return nullptr.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where the tail connects to form a cycle. If pos is -1, then there is no cycle.

Example:

Clarifying Questions

  1. What should be returned if there’s no cycle in the linked list?
    • Return nullptr if there’s no cycle.
  2. What is the range of values for the linked list nodes?
    • Each node’s value is an integer.
  3. What about the size of the linked list?
    • The size of the linked list can range from 0 to 10^4.
  4. Will there always be only one cycle in the linked list?
    • Yes, if a cycle exists, there’s only one cycle in the linked list.

Strategy

To detect the cycle and find the starting node of the cycle, we’ll use Floyd’s Tortoise and Hare algorithm:

  1. Detect the Cycle:
    • Use two pointers, a slow pointer (tortoise) and a fast pointer (hare).
    • Initially, both pointers are at the head of the linked list.
    • Move the slow pointer one step at a time.
    • Move the fast pointer two steps at a time.
    • If the linked list has a cycle, the slow and fast pointers will eventually meet.
    • If there’s no cycle, the fast pointer will reach the end of the linked list (nullptr).
  2. Find the Starting Node of the Cycle:
    • Once a cycle is detected, initialize another pointer at the head of the linked list.
    • Move both this new pointer and the slow pointer one step at a time.
    • The point at which they meet will be the start of the cycle.

Here’s the step-by-step code implementation:

Code

/**
 * 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) {
        if (!head) return nullptr;
        
        ListNode *slow = head;
        ListNode *fast = head;
        
        // Detect if there is a cycle
        while (fast != nullptr && fast->next != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
            
            if (slow == fast) {
                // Cycle detected, find the entry point of the cycle
                ListNode *entry = head;
                while (entry != slow) {
                    entry = entry->next;
                    slow = slow->next;
                }
                return entry; // The start of the cycle
            }
        }
        
        return nullptr; // No cycle
    }
};

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI