142. Linked List Cycle II – Solution [Brute-Force to Best]

Here’s the question link on Leetcode 142. Linked List Cycle II:

https://leetcode.com/problems/linked-list-cycle-ii/description

Brute Force – Using a Hash Set

We can store every visited node in an unordered_set.

While traversing the list:

  • If we encounter a node we’ve already visited, that’s where the cycle begins.
  • Otherwise, store the node and move forward.
  • If we reach NULL, there’s no cycle.
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        unordered_set<ListNode*> visited;

        ListNode* curr = head;

        while(curr != NULL) {
            if(visited.find(curr) != visited.end()) {
                return curr;
            }

            visited.insert(curr);
            curr = curr->next;
        }

        return NULL;
    }
};
142. Linked List Cycle II Solution

Optimal – Floyd’s Cycle Detection (Slow and Fast Pointers)

We can solve this using two pointers without any extra space.

First, we’ll use Floyd’s Cycle Detection:

  • slow moves one step at a time.
  • fast moves two steps at a time.
  • If they meet, a cycle exists.

But how do we find where the cycle starts?

Here’s the trick: After they meet, move slow back to the head. Keep fast at the meeting point. Now move both pointers one step at a time.

They will meet exactly at the starting node of the cycle.

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode* slow = head;
        ListNode* fast = head;

        // Detect the cycle
        while(fast != NULL && fast->next != NULL) {
            slow = slow->next;
            fast = fast->next->next;

            if(slow == fast) {
                break;
            }
        }

        // No cycle exists
        if(fast == NULL || fast->next == NULL) {
            return NULL;
        }

        // Find the starting node
        slow = head;

        while(slow != fast) {
            slow = slow->next;
            fast = fast->next;
        }

        return slow;
    }
};
142. Linked List Cycle II Solution

Leave a Reply