Start of LinkedList Cycle (medium)

Problem Statement #

Given the head of a Singly LinkedList that contains a cycle, write a function to find the starting node of the cycle.

Created with Fabric.js 1.6.0-rc.1 head 1 2 3 4 5 6 Cycle start Examples: Cycle start 1 2 3 4 5 6 1 2 3 4 5 6 head head Cycle start

Try it yourself #

Try solving this question here:

Output

0.714s

LinkedList cycle start: 1 LinkedList cycle start: 1 LinkedList cycle start: 1

Solution #

If we know the length of the LinkedList cycle, we can find the start of the cycle through the following steps:

  1. Take two pointers. Let’s call them pointer1 and pointer2.
  2. Initialize both pointers to point to the start of the LinkedList.
  3. 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.
  4. Move pointer2 ahead by ā€˜K’ nodes.
  5. Now, keep incrementing pointer1 and pointer2 until they both meet.
  6. As pointer2 is ā€˜K’ nodes ahead of pointer1, 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:

Created with Fabric.js 1.6.0-rc.1 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 pointer1 pointer2 pointer2 pointer1 pointer1, pointer2 1 2 3 4 5 6 pointer1, pointer2 -Keep incrementing both pointers until they meet -Move pointer2 '4' nodes ahead

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:

Output

0.479s

LinkedList cycle start: 3 LinkedList cycle start: 4 LinkedList cycle start: 1

Time Complexity #

As we know, finding the cycle in a LinkedList with ā€˜N’ nodes and also finding the length of the cycle requires O(N)O(N). Also, as we saw in the above algorithm, we will need O(N)O(N) to find the start of the cycle. Therefore, the overall time complexity of our algorithm will be O(N)O(N).

Space Complexity #

The algorithm runs in constant space O(1)O(1).

Mark as Completed
←    Back
LinkedList Cycle (easy)
Next    →
Happy Number (medium)