Given a linked list, check if the the linked list has loop or not. Below diagram shows a linked list with a loop.
We have discussed Floyd’s algorithm to detect cycle in linked list.
Brent’s cycle detection algorithm is similar to floyd’s algorithm as it also uses two pointer technique. But there is some difference in their approaches. Here we make one pointer stationary till every iteration and teleport it to other pointer at every power of two. The start of the cycle is determined by the smallest power of two at which they meet. This improves upon the constant factor of Floyd’s algorithm by reducing the number of calls.
- Move fast pointer (or second_pointer) in powers of 2 until we find a loop. After every power, we reset slow pointer (or first_pointer) to previous value of second pointer. Reset length to 0 after every every power.
- The condition for loop testing is first_pointer and second_pointer become same. And loop is not present if second_pointer becomes NULL.
- When we come out of loop, we have length of loop.
- We reset first_pointer to head and second_pointer to node at position head + length.
- Now we move both pointers one by one to find beginning of loop.
Comparison with Floyd’s Algorithm:
1) Finds the length of loop in first cycle detection loop itself. No extra work is required for this.
2) We only move second in every iteration and avoid moving first (which can be costly if moving to next node involves evaluating a function).
Loop is present at 15
Time Complexity: O(m + n) where m is the smallest index of the sequence which is the beginning of a cycle, and n is the cycle’s length.
Auxiliary Space : – O(1) auxiliary
- Reverse a singly Linked List in groups of given size | Set 3
- Remove all special characters from a singly Linked List
- Compare numbers represented by Linked Lists
- Header Linked List in C
- Clockwise rotation of Doubly Linked List by N places
- Generalized Linked List
- Convert a Singly Linked List to an array
- Clockwise rotation of Linked List
- Add the given digit to a number stored in a linked list using recursion
- Write a function to get the intersection point of two Linked Lists | Set 2
- Reverse even elements in a Linked List
- Insertion in a sorted circular linked list when a random pointer is given
- Merge K sorted Doubly Linked List in Sorted Order
- Traverse Linked List from middle to left-right order using recursion
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.