Skip to main content

Detect a Loop in Linked List

Problem Statement:​

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
  • Example:



✅ Solution: Two Pointer / Floyd's Cycle Detection (Tortoise and Hare)​

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

// Move slow by 1 and fast by 2 steps
while(fast != NULL && fast->next != NULL){
fast = fast->next->next;
slow = slow->next;

// If they meet, a cycle exists
if(fast == slow) return true;
}

return false; // No cycle
}
};


📝 How It Works​

  • We use two pointers:
    • slow moves one step at a time.
    • fast moves two steps at a time.
  • If there’s no cycle, fast will reach the end (NULL) and loop exits.
  • If there is a cycle, fast and slow will eventually meet inside the cycle.

This is known as Floyd’s Cycle Detection Algorithm (Tortoise and Hare).


🧩 Key Logic​

while(fast != NULL && fast->next != NULL){
fast = fast->next->next;
slow = slow->next;
if(fast == slow) return true;
}


⏱️ Time & Space Complexity​

MetricValue
TimeO(N)
SpaceO(1)
  • Each pointer travels at most N steps in the worst case.
  • No extra memory is used.

⚠️ Edge Cases​

  • Empty list (head == NULL)
  • Single node without cycle
  • Self-loop (single node pointing to itself)
  • Two-node cycle

💡 Other Approaches​

MethodTimeSpaceComment
HashSet TrackingO(N)O(N)Store visited nodes
Floyd’s AlgorithmO(N)O(1)Optimal and commonly preferred


🚀 Level Up Your Engineering Mindset

Never Study in Isolation. Join Binary Dose.

Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.

Discord
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚡
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

💡Have handwritten notes, cheat-sheets, or want to publish a technical article?
Learn How to Contribute→