Cycle detection algorithm