DEV Community


Posted on

LeetCode 142. Linked List Cycle II (javascript solution)


Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

Notice that you should not modify the linked list.


Time Complexity : O(n)
Space Complexity: O(1)

var detectCycle = function(head) {
    let slow = head;
    let fast = head;
    while(fast && &&{
        slow =;
        // Move fast pointer twice as fast as slow pointer and if there is a cycle, the fast will eventually meet slow at a node in the cycle but not necessarily the node that starts the cycle
        fast =;
        // Once we determine there is a cycle we must find where the cycle starts
        if(slow === fast){
            // Move slow pointer to the head
            slow = head;
            // Move both fast and slow pointer one node at a time and they will meet at the node where the cycle starts
            while(slow !== fast){
                slow =;
                fast =;
            return slow;
    return null;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)