Detecting a loop in a linked list is one of the most common and important problems in data structures. A loop in a linked list occurs when a node’s next
pointer points back to a previous node, forming a cycle. This problem is crucial for understanding linked lists and appears frequently in coding interviews.
In this blog, we will discuss:
- What a loop in a linked list is.
- Applications of detecting loops.
- Different approaches to solve the problem.
- Code implementations in Python.
- Time and space complexity analysis.
What is a Loop in a Linked List?
A loop, or cycle, in a linked list exists if the next
pointer of any node points back to one of the previous nodes in the list instead of null
. This causes an infinite traversal loop.
Example of a Linked List with a Loop:
Consider a linked list:1 -> 2 -> 3 -> 4 -> 5 -> 3 (back to 3)
In this example, the node with value 5
points back to the node with value 3
, forming a loop.

Applications of Detecting Loops
- Avoid Infinite Loops: Prevent endless traversal of the linked list in case of a loop.
- Memory Management: Identify and fix memory leaks caused by circular references in linked data structures.
- Algorithm Design: Detecting cycles is critical in graph-related problems, which are often represented using linked lists.
Approaches to Detect a Loop
1. Naive Approach: Using a Hash Table
Concept:
- Traverse the linked list and store the addresses of visited nodes in a hash table.
- If a node’s address is already in the table, a loop exists.
Algorithm Steps:
- Initialize an empty hash table.
- Traverse the linked list.
- For each node:
- Check if the node’s address is already in the hash table.
- If yes, a loop is detected.
- Otherwise, add the node’s address to the hash table.
- If the traversal ends, there is no loop.
Python Code:
class Node:
def __init__(self, data):
self.data = data
self.next = None
def detect_loop_hashing(head):
visited = set()
current = head
while current:
if current in visited:
return True # Loop detected
visited.add(current)
current = current.next
return False # No loop
# Example usage
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = head.next # Creates a loop
print("Loop detected (Hashing):", detect_loop_hashing(head))
Output:Loop detected (Hashing): True
2. Efficient Approach: Floyd’s Cycle Detection Algorithm

Detect Loop in a Linked List
Concept:
- Use two pointers:
- A slow pointer moves one step at a time.
- A fast pointer moves two steps at a time.
- If the list contains a loop, the slow and fast pointers will meet.
Algorithm Steps:
- Initialize two pointers:
slow
andfast
, both pointing to the head of the list. - Traverse the list:
- Move
slow
one step. - Move
fast
two steps. - If
slow
andfast
meet, a loop exists.
- If
fast
orfast.next
becomesnull
, no loop exists.
Python Code:
def detect_loop_floyd(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True # Loop detected
return False # No loop
# Example usage
print("Loop detected (Floyd's Algorithm):", detect_loop_floyd(head))
Output:Loop detected (Floyd's Algorithm): True
3. Modify the List: Marking Visited Nodes
Concept:
- Modify the
next
pointer of visited nodes to point to a dummy node or a specific value. - If a node already points to the dummy node, a loop exists.
Note: This method alters the linked list, which might not always be desirable.
Python Code:
def detect_loop_modify(head):
marker = Node(-1)
current = head
while current:
if current.next == marker:
return True # Loop detected
temp = current.next
current.next = marker
current = temp
return False # No loop
Comparison of Approaches
Approach | Time Complexity | Space Complexity | Notes |
---|---|---|---|
Hash Table | (O(n)) | (O(n)) | Simple but requires extra space. |
Floyd’s Algorithm | (O(n)) | (O(1)) | Most efficient method. |
Modify the List | (O(n)) | (O(1)) | Alters the structure of the list. |
Time and Space Complexity
Detect Loop in a Linked List
- Hash Table:
- Time Complexity: (O(n)) (traverse the list once).
- Space Complexity: (O(n)) (store node addresses).
- Floyd’s Cycle Detection:
- Time Complexity: (O(n)) (traverse the list once).
- Space Complexity: (O(1)) (uses two pointers only).
- Modify the List:
- Time Complexity: (O(n)).
- Space Complexity: (O(1)).
Special Cases
- Empty List:
If the linked list is empty (head == null
), there is no loop. - Single Node:
If the list has only one node pointing to itself, it is a loop. - Multiple Nodes with No Loop:
The traversal will terminate without detecting any loop.
FAQs
1. Can a doubly linked list have a loop?
Yes, loops can exist in doubly linked lists. The same detection methods can be applied.
2. How can we remove a detected loop?
You can traverse the list, find the node causing the loop, and set its next
pointer to null
.
3. Why is Floyd’s Algorithm efficient?
It detects loops in (O(n)) time using only (O(1)) space, making it ideal for large linked lists.
4. What are some real-world applications of loop detection?
- Memory management in operating systems.
- Cycle detection in network packets.
- Error handling in linked data structures.
5. Can we detect a loop without modifying the linked list?
Yes, Floyd’s Algorithm and the hash table approach both preserve the list structure.
Detecting a loop in a linked list is a critical operation in data structures. While the naive approach using a hash table is simple, Floyd’s Cycle Detection Algorithm is more efficient and widely preferred due to its (O(1)) space complexity. Understanding these methods will strengthen your grasp of linked list problems and pointer manipulation.
Read More –
How to Work with Virtual Environments in Python – https://kamleshsingad.com/wp-admin/post.php?post=5348&action=edit
Understanding Counting Sort: An In-Depth Guide – https://kamleshsingad.com/wp-admin/edit.php?post_type=post
The 6 Most Efficient Methods for Finding the Minimum Element in a Rotated Sorted Array – https://kamleshsingad.com/wp-admin/post.php?post=5440&action=edit
Also Read –
Enjoy Algorithms – Detect Loop in Linked List
EnjoyAlgorithmsLearn IT University – Loop Detection Guide
Learn IT UniversityGeeksforGeeks – Detect and Remove Loop in Linked List