views:

261

answers:

3

Possible Duplicates:
find whether a loop in a linked list without two pointers
How to determine if a linked list has a cycle using only two memory locations.
Best algorithm to test if a linked list has a cycle

During a preparation for a job interview, I encountered the following question:

How can you determine whether a linked list (of any type) contains a loop, using additional space complexity of O(1)? You cannot assume that the loop starts at the first node (and of course, the loop doesn't have to contain all nodes).

I couldn't find the answer, though I have the feeling it's quite simple...

+7  A: 

Easy. Maintain two pointers into the list. At each step, advance one pointer by a single link, and advance the other by two links. Test to see if they point to the same element. If so, you have a loop. If not, repeat until you find a loop or you reach the end of the list.

dty
I found that this solution was only "easy" if you knew it. This is, in my opinion, quite clever thinking.
Thanatos
Interesting. Why bother advancing the other at all?
T.E.D.
Any link may be equal to any other link, so they must both move around the list to test every (reachable) combination.
Ether
@T.E.D: The first node of the list may not be part of the cycle. IFF a cycle exists, there will be some i such that X_i = X_2*i, and the tortoise and hare algorithm finds the smallest such i if it exists.
Jim Lewis
Very creative :)
ET
Ahhhh. Thank you. The name sounds familiar, but my CS algorithms class was more than 20 years ago.
T.E.D.
A: 

Probably the same technique as checking if a graph is a tree (trees don't get to have cycles), see this this question. It recommends either a topological sort or a depth first search.

zdav
A: 

I had this exact problem in real live code last week.

All I did was kept a pointer (link) for the first element. Then as I iterated through the list, if I ever got that pointer again, I know there's a loop.

T.E.D.
See the comments on the accepted answer for why this won't catch *all* cycles, and why that is a better solution.
T.E.D.