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
- Sum of distances between the two nearest perfect squares to all the nodes of the given linked list
- Run Length Decoding in Linked List
- Find the balanced node in a Linked List
- Convert a given Binary Tree to Circular Doubly Linked List | Set 2
- Count duplicates in a given linked list
- Create new linked list from two given linked list with greater element at each node
- Divide the given linked list in two lists of size ratio p:q
- Create a linked list from two linked lists by choosing max element at each position
- Create linked list from a given array
- Sum of all odd frequency nodes of the Linked List
- Sum of smaller elements of nodes in a linked list
- Sum of all distinct nodes in a linked list
- Bubble Sort for Linked List by Swapping nodes
- Insert N elements in a Linked List one after other at middle position
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.