The task is to implement a function that detects a circle in a linked list.
The boilerplate code
function hasCircle(head) {
// your code here
}
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;
Move slow by 1, move fast by 2
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
}
If slow and fast become equal, it means a circle was found
if(slow === fast) {
return true;
}
If fast reaches the end, it means no circle was found.
return false;
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;
}
That's all folks!
Top comments (0)