Pergunta de entrevista da empresa SAP Ariba

find a loop in a list

Respostas da entrevista

Sigiloso

30 de mai. de 2009

use two iterators, one iterates the list one at a time, the other iterates two items at a time. If there is a loop in the list, these two iterators will cross path at some point.

Sigiloso

23 de jan. de 2011

By "list", is this a linked list? I don't see what other type of list makes sense. Actually, I'm pretty sure it's not O(n^2). If there is a loop, the worst case is that it loops back to the last element (this means the faster pointer will take the longest to reach the slow pointer). By the time the slow pointer reaches the point in the list where it loops back, the fast pointer will have caught up to it. So it's O(n).

Sigiloso

11 de fev. de 2010

the above is O(n^2), you can do much better. Single iterator plus a hash table (insert each value into hash table after searching for it in there). You get O(n).