Linked List Cycle
Easy
Linked ListTwo Pointers
Problem
Given the head of a linked list, return true if there is a cycle in it.
Example 1
Input: head = [3,2,0,-4], cycle at index 1
Output: true
Example 2
Input: head = [1,2], no cycle
Output: false
Constraints
- 0 ≤ length ≤ 10⁴
- −10⁵ ≤ val ≤ 10⁵
Approach — Two Pointers
This is a Two Pointers problem. The idea: walk two indices through the data together (or toward each other), turning an O(n²) pair search into one linear pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(1) extra space.
Solution code
Python
class Solution:
def hasCycle(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False
Java
class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Linked List Cycle interactively → ← All solutions