</>

141. Linked List Cycle

Easy NeetCode 150
Linked List Time O(N) Space O(1)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Linked List
Time
O(N)
Space
O(1)

Standard Solution (C++)

SummaryGiven the head of a singly-linked list, determine whether the list contains a cycle — that is, whether any node's `next` pointer eventually leads back to a previously visited node.

Approach
  • Use Floyd's two-pointer (tortoise and hare) algorithm: a slow pointer advances one step at a time while a fast pointer advances two steps at a time.
  • If a cycle exists, the fast pointer will eventually lap the slow pointer and they will meet at the same node.
  • If the list is acyclic, the fast pointer will reach a null next pointer and the loop terminates, returning false.
  • This approach requires no extra memory because it relies solely on pointer arithmetic.
#include <cstddef>
using namespace std;

// Definition for singly-linked list.
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

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

        // Advance fast by 2, slow by 1 each iteration.
        // If fast ever catches slow (after starting), a cycle exists.
        while (fast != nullptr && fast->next != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) return true;  // pointers met — cycle detected
        }

        return false;  // fast reached end — no cycle
    }
};
Time O(n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(!head) return false;
        ListNode *fast=head;
        ListNode *slow=head;
        while(fast->next && fast->next->next){
            slow=slow->next;
            fast=fast->next->next;
            if(slow==fast) return true;
        }
        return false;
    }
};

// Time Complexity: O(N)
// Space Complexity: O(1)
Time O(N) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern