Search for a command to run...
Detect cycle with slow/fast pointers, then freeze slow and revolve fast to count loop length
Phase 1: Detect Cycle
Initialize slow and fast pointers at the head of the list.
Floyd's Loop Length Counting
1class Solution {2 findLength(slow, fast) {3 let cnt = 1;4 fast = fast.next;5 6 while (slow !== fast) {7 cnt++;8 fast = fast.next;9 }10 return cnt;11 }12 13 findLengthOfLoop(head) {14 let slow = head;15 let fast = head;16 17 while (fast !== null && fast.next !== null) {18 slow = slow.next;19 fast = fast.next.next;20 21 if (slow === fast) {22 return this.findLength(slow, fast);23 }24 }25 return 0;26 }27}