DEV Community

Discussion on: Loop detection - Google interview question

Collapse
 
techschoolguru profile image
TECH SCHOOL

This cycle detection in functional graph problem can be solved by the Floyd's Tortoise and Hare algorithm in O(P+L) time and O(1) memory, where P is the start point of the loop, and L is the length of the loop: en.wikipedia.org/wiki/Cycle_detection

TL;DR?
The basic idea is, for all i >= P, we have f(i) = f(i+k*L), because all points after P is in the loop, so:

  1. f(k*L) = f(2*k*L) => there must exist a point x=k*L in the loop that f(x) = f(2*x) => if a hare and a tortoise start their race at 0, and the hare moves 2 times as fast as the tortoise, they will meet at the point x=k*L in the loop.
  2. f(P) = f(P+k*L) => when the hare and the tortoise meet at x=k*L, if we reset the hare's position to 0 and set its speed to be the same as the tortoise, then after P steps, they will meet again at P, or the starting point of the loop => this is the point we want to find.
Collapse
 
rodiongork profile image
Rodion Gorkovenko

Thanks a lot! It never occurred to me that such question even has several named algorithms. Hare-and-Tortoise obviously couldn't be applied as is (because we have single function to call and it has some state) - but obviously it will fit in some modified version, especially if we allow restarting generator.

I'll send the link to your comment to my fellow, so thanks from him too, beforehand :)