Cycle Detection
“Floyd’s cycle-finding algorithm is a pointer algorithm that uses only two pointers, which move through the sequence at different speeds”
References
Implementations
-
1
# TODO: Implement in Python -
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
var listHasCycle = function(head) { // 1. is there a cycle? let slow = head.next let fast = head.next.next while (slow !== fast) { slow = slow.next fast = fast.next.next } // 2. where does the cycle start? let cycleStartPosition = 0 slow = head while (slow !== fast) { slow = slow.next fast = fast.next cycleStartPosition += 1 } // 3. what is the length of the cycle? let cycleLength = 1 fast = slow.next while (slow !== fast) { fast = fast.next cycleLength += 1 } return { cycleLength, cycleStartPosition, } } // log { const res = listHasCycle(list) logTracer.print(`cycle start position: ${res.cycleStartPosition}`) logTracer.print("\n") logTracer.print(`cycle length: ${res.cycleLength}`)