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
}

Using two pointers, one pointer moves one step at a time, and the second pointer moves two steps…


This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan

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!


This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan


Print Share Comment Cite Upload Translate Updates
APA

Bukunmi Odugbesan | Sciencx (2025-11-19T23:28:32+00:00) Coding Challenge Practice – Question 60. Retrieved from https://www.scien.cx/2025/11/19/coding-challenge-practice-question-60/

MLA
" » Coding Challenge Practice – Question 60." Bukunmi Odugbesan | Sciencx - Wednesday November 19, 2025, https://www.scien.cx/2025/11/19/coding-challenge-practice-question-60/
HARVARD
Bukunmi Odugbesan | Sciencx Wednesday November 19, 2025 » Coding Challenge Practice – Question 60., viewed ,<https://www.scien.cx/2025/11/19/coding-challenge-practice-question-60/>
VANCOUVER
Bukunmi Odugbesan | Sciencx - » Coding Challenge Practice – Question 60. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/11/19/coding-challenge-practice-question-60/
CHICAGO
" » Coding Challenge Practice – Question 60." Bukunmi Odugbesan | Sciencx - Accessed . https://www.scien.cx/2025/11/19/coding-challenge-practice-question-60/
IEEE
" » Coding Challenge Practice – Question 60." Bukunmi Odugbesan | Sciencx [Online]. Available: https://www.scien.cx/2025/11/19/coding-challenge-practice-question-60/. [Accessed: ]
rf:citation
» Coding Challenge Practice – Question 60 | Bukunmi Odugbesan | Sciencx | https://www.scien.cx/2025/11/19/coding-challenge-practice-question-60/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.