Start of LinkedList Cycle (medium)
We'll cover the following
Problem Statement #
Given the head of a Singly LinkedList that contains a cycle, write a function to find the starting node of the cycle.
Try it yourself #
Try solving this question here:
Solution #
If we know the length of the LinkedList cycle, we can find the start of the cycle through the following steps:
- Take two pointers. Letās call them
pointer1
andpointer2
. - Initialize both pointers to point to the start of the LinkedList.
- We can find the length of the LinkedList cycle using the approach discussed in LinkedList Cycle. Letās assume that the length of the cycle is āKā nodes.
- Move
pointer2
ahead by āKā nodes. - Now, keep incrementing
pointer1
andpointer2
until they both meet. - As
pointer2
is āKā nodes ahead ofpointer1
, which means,pointer2
must have completed one loop in the cycle when both pointers meet. Their meeting point will be the start of the cycle.
Letās visually see this with the above-mentioned Example-1:
We can use the algorithm discussed in LinkedList Cycle to find the length of the cycle and then follow the above-mentioned steps to find the start of the cycle.
Code #
Here is what our algorithm will look like:
Time Complexity #
As we know, finding the cycle in a LinkedList with āNā nodes and also finding the length of the cycle requires . Also, as we saw in the above algorithm, we will need to find the start of the cycle. Therefore, the overall time complexity of our algorithm will be .
Space Complexity #
The algorithm runs in constant space .