How to detect a loop in a linked list?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
A linked list is a fundamental data structure used extensively in computer science for organizing data in a sequential manner. It comprises a series of nodes, each having a data payload and a reference (or link) to the next node in the sequence. A linked list can be either singly linked or doubly linked. However, one potential issue with linked lists is the existence of loops. A loop in a linked list signifies that the list, although finite, forms a cycle wherein certain nodes are revisited, creating a non-terminating sequence. Detecting such loops is crucial for algorithm optimization and preventing infinite processing sequences.
Detecting a Loop in a Linked List
There are multiple algorithms for detecting loops in a linked list. We'll discuss the most prevalent techniques, such as the Floyd’s Cycle-Finding Algorithm (also known as the Tortoise and Hare Algorithm), and the Hash Table Method.
1. Floyd's Cycle-Finding Algorithm
Floyd's Cycle-Finding Algorithm is a popular method for detecting a loop in a linked list due to its efficiency and simplicity. It employs two pointers moving at different speeds through the linked list.
How It Works:
- Initialization: Begin with two pointers,
slowandfast. Both pointers start at the head of the linked list. - Movement: Move
slowby one step andfastby two steps in each iteration. - Detection: If a loop exists,
slowandfastwill eventually meet at the same node due to the cyclical nature. If there is no loop in the list,fastwill reach the end of the list (i.e.,null).
Complexity:
- Time Complexity: O(n), where n is the number of nodes in the linked list.
- Space Complexity: O(1), as no extra space is needed.
Example Code (Python):
2. Hash Table Method
The Hash Table Method leverages a hash table (or set) to keep track of visited nodes.
How It Works:
- Traversal: Traverse each node in the linked list.
- Storage: For each node, check if it has been encountered before by storing visited nodes in a hash table.
- Detection: If a node is encountered that already exists in the hash table, a loop is present. If you reach the end of the list (null), no loop exists.
Complexity:
- Time Complexity: O(n), due to the traversal of the list.
- Space Complexity: O(n), because of the space taken by the hash table to store nodes.
Example Code (Python):
Comparison of Methods
Here's a quick summary of the two main techniques mentioned:
| Method | Time Complexity | Space Complexity | Pros | Cons |
| Floyd's Cycle-Finding | O(n) | O(1) | Efficient in both time and space | More challenging to implement |
| Hash Table Method | O(n) | O(n) | Simplicity in implementation | Higher space consumption |
Additional Topics
Detecting the Starting Point of a Loop
Upon detecting a loop using Floyd's method, it's possible to find the starting point of the loop:
- When the two pointers
slowandfastmeet, keepfastat the meeting point. - Move
slowback to the head of the list. - Move both pointers one step at a time. The point where they meet again will be the starting point of the loop.
Handling Special Cases
- Empty List: An empty list naturally has no loop.
- Single Node with Loop: A single node pointing to itself forms a loop. Both methods can detect this efficiently.
- Various Configurations: Implement robust test cases to ensure your loop identification algorithms work correctly across different list structures.
Conclusion
Detecting a loop in a linked list is a crucial capability for many applications, including memory management and real-time systems. The choice of detection algorithm depends on specific constraints such as processing time and memory usage. While Floyd's method is efficient and space-conservative, the Hash Table method is simpler to implement, albeit more memory-intensive. Nonetheless, both techniques are potent tools for ensuring linked list integrity and enhancing algorithm robustness.
Related reading
- How to detect cycles in a directed graph using the iterative version of DFS?
- How to detect if a directed graph is cyclic?
- How to detect if an ellipse intersectscollides with a circle
- How to detect if the given graph has a cycle containing all of its nodes? Does the suggested algorithm have any flaws?
- How to determine if a JavaScript array contains an object with an attribute that equals a given value
- How to determine if a linked list has a cycle using only two memory locations
- How to determine day of week by passing specific date?
- How to determine if a Delaunay triangle is internal or external?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.