Skip to content
thesarfo

Reference

Linked List Cycle

Detecting whether a linked list contains a cycle — a HashSet approach vs. Floyd's Tortoise and Hare in constant space.

views 0

Given the head of a singly linked list, determine if the linked list contains a cycle — a cycle occurs if some node can be reached again by continuously following the next pointer. Unlike finding where the cycle begins, you only need to detect whether a cycle exists. (LeetCode 141)

Approach 1 — HashSet (O(n) space): traverse the list, storing each visited node in a set. If a node is revisited, there is a cycle.

public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> visited = new HashSet<>();
ListNode current = head;
while (current != null) {
if (visited.contains(current)) {
return true;
}
visited.add(current);
current = current.next;
}
return false;
}
}

Approach 2 — Floyd’s Tortoise and Hare (O(1) space): if the list contains a cycle, slow and fast will eventually meet.

public 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;
}
}

Why this works: if there’s a cycle, the faster-moving pointer will eventually “lap” the slower one inside the loop, causing them to meet.