linked list
loop detection
algorithms
data structures
computer science

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

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, slow and fast. Both pointers start at the head of the linked list.
  • Movement: Move slow by one step and fast by two steps in each iteration.
  • Detection: If a loop exists, slow and fast will eventually meet at the same node due to the cyclical nature. If there is no loop in the list, fast will 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):

python
1class ListNode:
2    def __init__(self, value=0, next=None):
3        self.value = value
4        self.next = next
5
6def has_cycle(head: ListNode) -> bool:
7    if not head:
8        return False
9
10    slow, fast = head, head
11
12    while fast and fast.next:
13        slow = slow.next
14        fast = fast.next.next
15        if slow == fast:
16            return True
17    
18    return False

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):

python
1def has_cycle_hashmap(head: ListNode) -> bool:
2    visited = set()
3    current = head
4    
5    while current:
6        if current in visited:
7            return True
8        visited.add(current)
9        current = current.next
10    
11    return False

Comparison of Methods

Here's a quick summary of the two main techniques mentioned:

MethodTime ComplexitySpace ComplexityProsCons
Floyd's Cycle-FindingO(n)O(1)Efficient in both time and spaceMore challenging to implement
Hash Table MethodO(n)O(n)Simplicity in implementationHigher 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:

  1. When the two pointers slow and fast meet, keep fast at the meeting point.
  2. Move slow back to the head of the list.
  3. 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
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.