Alex Rivera | Logout

How to find the length of a linked list that is having cycles in it?

Asked 2010-05-05T12:08:25.670
10

This was one of the interview questions asked. How to find the length of a linked list that is having cycle in it. I know how to calculate whether a linked list has a cycle or not using Hare and Tortoise technique. I even know how to calculate the length by storing the addresses in a hashset. The running time of the Algorithm should be O(n).

But what I was not able to tell is how to calculate the length of the linked list without using a external space of O(n). Please help me. Thank you.

Edit
Report

2 Answers

4
  1. Apply Tortoise and Hare algorithm and stop when characters meet
  2. Continue iterating through the list only with Tortoise and reverse each link it will pass

The number of reversed links is the length of the cycle

answered 2010-05-07T20:44:28.710
1

Detect loop point By (Slow pointer and fast pointer approach), find the loop detection node

Now take pointers P1 and P2, P1 at the loop detection node and P2 starting from head of the linked list Traverse both the pointers one at a time

Both the pointers meet at the node because of which there is a loop in the linked list

Use the standard fast and slow pointer algorithm find the loop detection point

Take two pointers P1 and P2 at loop detection point. Place pointer P1 at the same place and move P2 forward one step at a time. Repeat until both the pointers meet together. Keep a count variable incremented for every iteration which gives length of the loop. Let say the length is L1

Again take two pointers P1 and P2. P1 at the head of the linked list and P2 at the loop detection point. Forward both the pointers one step at a time. Repeat until both the pointers meet together. This procedure is equivalent to the one we use to calculate node that causes loop in a linked list. Keep a count variable incremented for every iteration which gives the length of the list until the merging point. Let say the length is L2 Now the length of the list that contains loop is L1+ L2

answered 2013-02-14T17:49:39.527

Your Answer