Microsoft Interview Question

How to detect loops on a single linked list?

Interview Answer

Anonymous

May 26, 2009

Use two pointers to the elements in the list. They both move forward in the linked list. The first one moves one unit at a time while the second one moves two times (1 2 2 1 2 2 1 2 2 1 2 2 etc). If they ever collide after incrementing the value (point to the same element), then the list has cycles. If the fastest one reaches the end of the list, then the list doesn't have cycles. Big O: O(n)