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

Here’s the question link on Leetcode 141. Linked List Cycle:-

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

Brute Force – Using a Hash Set

We can keep track of all the nodes we’ve already visited using an unordered_set.

While traversing the list:

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

        ListNode* temp = head;

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

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

        return false;
    }
};
141. Linked List Cycle Brute Force Solution

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

We can solve this without extra space using two pointers:

  • slow moves one step at a time.
  • fast moves two steps at a time.

If there’s no cycle, fast will eventually reach NULL.

But if a cycle exists, fast will eventually catch up with slow. They’ll meet at the same node.

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

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

            if(slow == fast) {
                return true;
            }
        }

        return false;
    }
};
141. Linked List Cycle Optimal Solution

Leave a Reply