Search for a command to run...
Use Floyd's Tortoise and Hare algorithm to detect cycles in O(n) time and O(1) space
Initialization
slow and fast pointers set to head.
Floyd's Cycle Finding
1class Solution {2 hasCycle(head) {3 let slow = head;4 let fast = head;5 6 while (fast !== null && fast.next !== null) {7 slow = slow.next;8 fast = fast.next.next;9 10 if (slow === fast) {11 return true; // Loop detected12 }//slow: 1fast: 113 }14 15 return false;16 }17}