JavaScript Solution


  • 0
    O

    Same as the top solution using tortoise - hare algorithm (Floyd's cycle detection):

    https://www.quora.com/How-does-Floyds-cycle-finding-algorithm-work

    var detectCycle = function(head) {
        if (!head || !head.next) return null;
        
        let slow = head;
        let fast = head.next;
        
        while (slow !== fast) {
            slow = slow.next;
            if (!fast.next || !fast.next.next) return null;
            fast = fast.next.next;
        }
        
        // Key step: once we move fast to head, we need to update slow to slow.next. 
        // This is because we are using the next tick as the starting point.
        fast = head;
        slow = slow.next;
        
        while (slow !== fast) {
            slow = slow.next;
            fast = fast.next;
        }
        
        return fast;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.