0

Question: To find starting node of loop if cycle exists in linked list

Approach:

(1)Using Hare-Tortoise algorithm, find if cycle exists(No issues with this step)

(2)Let P be the node where hare and tortoise meets.Let H be head pointer on linked list.Traverse one node at a time from H and P until they meet.

Doubt: Logic behind (2). How does traversing one step at a time from H and P ensure that they will meet at the start of loop?

References:

Problem and Solution

Partially Explained Logic(Refer second approach in this blog)

1 Answer 1

1

Let T be the number of links traversed by the tortoise, and let S be the number of links traversed before reaching the cycle.

We know that traveling T links along the cycle puts you back where you started, since the tortoise and the hare reach the same spot P after traveling T and 2T links respectively. If you travel S links from P, this is equivalent to traveling S links from the start and then traveling T links, which is equivalent to just traveling S links from the start.

Thus, when the pointer traveling from the start of the list has traveled S links, it reaches the start of the cycle, and it meets up with the pointer traveling from P.

Sign up to request clarification or add additional context in comments.

2 Comments

"We know that traveling T links along the cycle puts you back where you started, since the tortoise and the hare reach the same spot P after traveling T and 2T links respectively". This is my doubt. How do we know? Please elaborate
@user3409814: Seriously? That's the part that confuses you? Okay, suppose you travel T links from the start. You reach the tortoise's location, which is P. You keep traveling for another T links. You reach the hare's location, which is also P. Therefore, traveling T links from P puts you back at P. By the symmetry of the cycle's structure, we can tell that traveling T links from any point in the cycle will put you back where you started.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.