Domanda di colloquio di Goldman Sachs

How to find whether a linked list has a loop within it.

Risposte di colloquio

Anonimo

6 apr 2011

Use 2 pointers, varying the speeds of both. If at sometime they meet each other, that means there exists a loop, else if the reach the end of linked list that means there does not exists a loop.

Anonimo

7 apr 2011

The previous answer has an indefinite worst case running time, which usually is something you want to avoid. You can search through the list once adding the pointer addresses to a hashmap. If ever you reach an address that already exists in the hashmap, then there is a loop. In the worst case you have to read through the whole list once. On average, you have to read (n+1)/2 elements.

Anonimo

13 mag 2011

While traversing the list from the starting node, you can leave a mark behind, if you encounter a mark in a node, then it's linked. If you reach the end without finding your mark, then it is not linked.

Anonimo

13 mag 2011

linked => circular

Anonimo

18 feb 2013

The following blog discussed this problem in details: http://codercareer.blogspot.com/2012/01/no-29-loop-in-list.html