Algorithm Code
Time: O(n) | Space: O(1)
1function hasCycle(head) {
2 let slow = head;
3 let fast = head;
4
5 while (fast && fast.next) {
6 slow = slow.next; // Move slow by 1
7 fast = fast.next.next; // Move fast by 2
8
9 if (slow === fast) {
10 return true; // Cycle detected
11 }
12 }
13
14 return false; // No cycle
15}Algorithm Steps
Step 1 of 5
1
Initialize Pointers
Set both slow and fast pointers to head (index 0)
2
Move Pointers
Slow pointer at index 1, Fast pointer at index 2
3
Move Pointers
Slow pointer at index 2, Fast pointer at index 4
4
Move Pointers
Slow pointer at index 3, Fast pointer at index 5
5
No Cycle Detected
Fast pointer reached the end - no cycle in the list
Linked List
0
1
Slow
Fast
→
1
2
→
2
3
→
3
4
→
4
5
→
5
6
Fast & Slow Pointers Technique
Slow Pointer: Moves 1 step at a time
Fast Pointer: Moves 2 steps at a time
Use Case: Cycle detection, finding middle element
Slow
Fast
Both
Visited
Step 0 of 40%
0.25x4x