DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 60

The task is to implement a function that detects a circle in a linked list.

The boilerplate code

function hasCircle(head) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

Using two pointers, one pointer moves one step at a time, and the second pointer moves two steps at a time. Both start at the head of the linked list

let slow = head;
let fast = head;
Enter fullscreen mode Exit fullscreen mode

Move slow by 1, move fast by 2

while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
}
Enter fullscreen mode Exit fullscreen mode

If slow and fast become equal, it means a circle was found

if(slow === fast) {
return true;
}
Enter fullscreen mode Exit fullscreen mode

If fast reaches the end, it means no circle was found.

return false;
Enter fullscreen mode Exit fullscreen mode

The final code

function hasCircle(head) {
  // your code here
  if(!head) return false;

  let slow = head;
  let fast = head;

  while(fast && fast.next) {
    slow = slow.next;
    fast = fast.next.next;

    if(slow === fast) {
      return true;
    }
  }
  return false;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)