Introduction
The Detect Cycle in a Linked List problem is a popular DSA interview question. It is frequently asked because it tests your understanding of pointers, traversal logic, and problem optimization.
In simple words, this problem asks you to check whether a linked list contains a loop (cycle) or not.
This article explains the problem in very simple, human-friendly language, from basic concepts to interview-level depth, using Floyd’s Cycle Detection Algorithm.
What is a Cycle in a Linked List?
A cycle (loop) in a linked list occurs when a node’s next pointer points to one of the previous nodes instead of pointing to null.
Because of this:
Traversal never ends
The list becomes infinite
Example of a Cycle
1 → 2 → 3 → 4 → 5
↑ ↓
← ← ← ← ←
Here, node 5 points back to node 3, creating a cycle.
Why Detecting a Cycle is Important
Detecting cycles is important because:
Infinite loops can crash programs
Memory leaks may occur
Many real-world systems (OS, networking) use cycle detection
Interviewers use this problem to test pointer logic and optimization skills.
Brute Force Approach (Not Recommended)
One simple idea is to store visited nodes in a data structure.
How it Works
Traverse the list
Store each visited node in a HashSet
If a node appears again, a cycle exists
Problems with This Approach
Extra space is required
Space Complexity becomes O(n)
Interviewers usually expect a better solution.
Optimized Approach: Floyd’s Cycle Detection Algorithm
The best and most popular solution is Floyd’s Cycle Detection Algorithm, also known as the Tortoise and Hare Algorithm.
Key Idea (Very Simple)
Use two pointers:
Slow pointer moves one step at a time
Fast pointer moves two steps at a time
If a cycle exists, the fast pointer will eventually meet the slow pointer
If they meet → cycle exists
If fast pointer reaches null → no cycle
Why Floyd’s Algorithm Works
In a cycle:
Fast pointer moves faster
It will eventually lap the slow pointer
This guarantees a meeting point inside the cycle.
Step-by-Step Explanation
Steps:
Initialize both
slowandfastat the headMove
slowby one step andfastby two stepsIf
slow == fast, a cycle is detectedIf
fastorfast.nextbecomesnull, no cycle exists
Join the conversation! Your thoughts help the community grow.