Linked List
Data Structures
Programming
Loop Detection
Algorithms

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.

Practice algorithms

Detecting a loop in a linked list is a common challenge in computer science, often encountered when dealing with complex data structures. A loop in a linked list occurs when a node’s next pointer points back to a previous node in the list. This results in a cycle that can cause algorithms to enter infinite loops or other unwanted behaviors. Understanding how to identify these loops is crucial for maintaining robust and efficient applications.

Strategies to Detect a Loop

There are several techniques to detect a loop in a linked list:

  1. Hashing Approach: The idea is to traverse the list and store each node's reference in a hash table. If a node appears more than once in the hash table, a loop exists.
  2. Floyd’s Cycle-Finding Algorithm (Tortoise and Hare): This approach involves two pointers, slow and fast (also known as tortoise and hare). The slow pointer moves one step at a time, while the fast pointer moves two steps. If there is a loop, the fast pointer will eventually meet the slow pointer within the loop.
  3. Brent's Algorithm: Similar to Floyd's, this algorithm also uses two pointers but with distinct moving strategies, potentially offering better performance regarding iterations and space.

Floyd’s Cycle-Finding Algorithm Detailed Explanation

The algorithm known as "Floyd's Cycle-Finding" is particularly popular due to its efficiency and simplicity. Here is a step-by-step approach:

  1. Initialization: Start with two pointers, slow and fast, which both point to the head of the linked list.
  2. Movement: Move the slow pointer by one step and the fast pointer by two steps. Continue this process until either they meet or the fast pointer reaches the end of the list.
  3. Meeting Point: If the fast pointer reaches the end, the list doesn’t have a loop. If the slow and fast pointers meet, then a loop exists.
  4. Finding the Entrance of the Loop: To find the entry point of the loop, reset one pointer to the head while keeping the other at the meeting point. Move both one step at a time; the node where they meet next is the start of the loop.

Example in Code

Here's a simple implementation in Python:

python
1class Node:
2    def __init__(self, value):
3        self.value = value
4        self.next = None
5
6def detect_loop(head):
7    slow = fast = head
8    while fast and fast.next:
9        slow = slow.next
10        fast = fast.next.next
11        if slow == fast:
12            return True  # Loop detected
13    return False  # No loop
14
15# Example usage:
16# Let's create a linked list with a loop for demonstration:
17# 1 -> 2 -> 3 -> 4 -> 5 -> 3 ...
18head = Node(1)
19head.next = Node(2)
20third_node = Node(3)
21head.next.next = third_node
22head.next.next.next = Node(4)
23head.next.next.next.next = Node(5)
24head.next.next.next.next.next = third_node
25
26print(detect_loop(head))  # Output will be True

Comparison of Techniques

TechniqueSpace ComplexityTime ComplexityImplementation Complexity
HashingO(n)O(n)O(n)O(n)Simple
Floyd’s Cycle-FindingO(1)O(1)O(n)O(n)Simple
Brent's AlgorithmO(1)O(1)O(n)O(n)Moderate

Conclusion

Detecting loops in linked lists is essential for avoiding infinite loops and crashes in applications that implement linked lists. Floyd’s Cycle-Finding Algorithm offers a balance between efficiency and ease of implementation, making it highly popular. Understanding these techniques adds a valuable tool to any developer's arsenal when dealing with linked lists and other circular data structures.


Related reading
Course
Intermediate
27 lessons
15 hours
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 course
Track 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.

Practice algorithms

All Rights Reserved.