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
- Merge K sorted Doubly Linked List in Sorted Order
- Traverse Linked List from middle to left-right order using recursion
- Move last element to front of a given Linked List | Set 2
- Python | Stack using Doubly Linked List
- Python | Queue using Doubly Linked List
- Adding two polynomials using Linked List using map
- Remove Nth node from end of the Linked List
- Subtraction of the alternate nodes of Linked List
- Maximum sum contiguous nodes in the given linked list
- Introduction to Data Structures | 10 most commonly used Data Structures
- Splitting starting N nodes into new Circular Linked List while preserving the old nodes
- Add the given digit to a number stored in a linked list
- Find the first duplicate element in the linked list
- Add one to a number represented as linked list | Set 2
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.