## DEV Community is a community of 626,822 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# LeetCode 142. Linked List Cycle II (javascript solution)

### Description:

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.

### Solution:

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

``````var detectCycle = function(head) {
while(fast && fast.next && fast.next.next){
slow = slow.next;
// 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 = fast.next.next;
// Once we determine there is a cycle we must find where the cycle starts
if(slow === fast){
// Move slow pointer to the head