Linked List Cycle
Easy · Linked lists
Jump to codeDetermine whether repeatedly following next pointers in a singly linked list can revisit a node. Compare node identity, not values.
Examples
Example 1
head = [3,2,0,-4] pos = 1
Output: true
Example 2
head = [1,2] pos = 0
Output: true
Constraints
- 1 <= Length of the list <= 1000.
- -1000 <= Node.val <= 1000
- pos is -1 or a valid index in the linked list.
Function contract
Linked lists are displayed as value arrays. Your code receives ListNode objects with val and next fields.
head is built from the values array; pos is the zero-based index that the tail links to, or -1 for no cycle. Your function receives head, not pos.
Need a hint?
Two runners moving at different speeds eventually meet inside a cycle.
Asked in real interviews
Candidates reported versions of Linked List Cycle from these company interviews. Some company questions are locked and open with Premium or XP.
Browse all real coding interview questionsSolution approach
Move slow by one link and fast by two. If they reference the same node after moving, return true. If fast or fast.next becomes null, return false. Repeated values in different nodes do not imply a cycle.
Complexity
O(n) time and O(1) space.
Python reference solution
def hasCycle(head):
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast:
return True
return False
JavaScript solution
function hasCycle(head) {
let slow = head, fast = head;
while (fast && fast.next) {
slow = slow.next; fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}
Java solution
import java.util.*;
class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next; fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool hasCycle(ListNode* head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next; fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 7 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
3,
2,
0,
-4
],
1
]true
[
[
1,
2
],
0
]true
[
[
1
],
-1
]false
[
[
1,
2,
3
],
-1
]false
[
[
1,
2,
3,
4
],
2
]true
Drafts are saved per language in this browser when storage is available.