Linked List Cycle in Java: Detect Loops with a HashSet and Floyd’s Tortoise and Hare
-
Last Updated: November 13, 2026
-
By: javahandson
-
Series

Detect a Linked List Cycle in Java DSA two ways: a HashSet of nodes and Floyd’s Tortoise and Hare. Full 7-node dry runs, clean code, and complexity notes.
Linked List Cycle in Java is a classic interview warm-up that checks one simple thing. Does the list quietly loop back on itself, or does it end cleanly at null? A cycle means some node points back to an earlier node. So you keep walking forever and never reach a real end.
The task sounds tricky, but the rules are short. You get the head of a singly linked list. You return true when a cycle exists, and false when the list stops in the normal way.
We build the answer in two clear steps. First we track the nodes we have already seen using a HashSet. Then we switch to Floyd’s Tortoise and Hare, a two pointer trick that needs almost no extra memory.
Both approaches get a full, step by step dry run on the same seven node list. Nothing gets skipped along the way. You can watch each pointer move and see exactly why the answer turns out true or false.
Let us pin down the rules before we touch any code.
head node of a singly linked list.For our walkthrough we use a list of seven nodes. We label them A to G, so each node has a clear name of its own. The values, in order, are 3, 2, 0, 4, 7, 1, and 9.
In the cycle version, node G does not point to null. Instead G points back to node C, so the tail loops into the middle. In the clean version, node G points to null and the list ends like a normal chain.
Here is the node class we work with. Each node holds one value and one link to the next node.
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}A linked list is a chain of nodes joined by arrows. Each node is a small box that holds two things. One is a value, like a number. The other is a pointer called next, which is simply an arrow to the box that comes after it.
You cannot jump straight to the fifth node the way you would in an array. Instead you start at the head and follow the arrows one at a time. The last node points its arrow at null, and that null is how you know the chain has ended.
next again and again, and you walk the whole list from start to end.next is the natural stop sign that says nothing comes after this node.Picture a running track that loops back on itself. Once a node points backward, your walk has no finish line. You just keep going around the same nodes forever. So detecting a cycle really means catching that endless loop before your code gets stuck in it.
This idea trips up many beginners, so let us slow right down. Two different boxes can hold the same number. Yet they are still two separate boxes, sitting at different spots in memory.
When we check whether a node was seen before, we must compare the box itself, not the number inside it. In Java, that means comparing the node object, never its val field.
HashSet of nodes remembers the actual boxes we have already visited.Here is why this matters for our example. The list holds values like 3, 2, and 0. If two separate nodes both held 0, a value check would shout cycle even on a straight list. Comparing the boxes themselves keeps the answer honest.
Floyd’s trick runs two pointers on the same list at once. One is slow and moves a single node each turn. The other is fast and moves two nodes each turn. People nickname them the tortoise and the hare for that reason.
That steady gain is the real secret. The gap between the two shrinks by one node each turn, so it must reach zero at some point. When the gap hits zero, both pointers sit on the same node, and that meeting is your proof of a cycle.
The first idea is direct and easy to trust. Walk the list one node at a time, and remember every node you touch. If you ever reach a node that is already remembered, the list has looped. If you fall off the end into null, it has not.
seen = empty set of nodes
current = head
while current is not null:
if current is in seen:
return true
add current to seen
current = current.next
return falseThink of the set as a guest list of nodes we have already let in. We walk the list from the head, and at every node we ask one question before doing anything else.
current.next.current turns null, we hit a real end, so there is no cycle and we return false.The order of these steps matters a lot. We always check first, and only then add. If we added before checking, every node would look brand new, so we would never catch the repeat. Checking first is exactly what lets the second visit to a looped node fire the true answer.
import java.util.*;
public class LinkedListCycleSet {
public static boolean hasCycle(ListNode head) {
Set<ListNode> seen = new HashSet<>();
ListNode current = head;
while (current != null) {
if (seen.contains(current)) {
return true;
}
seen.add(current);
current = current.next;
}
return false;
}
}The Java code is that same guest-list idea, now in real syntax. The one helper to know is HashSet, a collection that stores objects and answers membership checks very fast.
HashSet of ListNode. Notice it holds node objects, which is exactly the identity check we need.current at the head, so our walk begins at the first node.current is a real node and not null.seen.contains(current) first. A true answer means we looped, so line 10 returns true at once.current forward with current.next, taking one step down the chain.current turned null, which signals a clean end and no cycle.A quick word on speed. Each contains and add call on a HashSet runs in about constant time. So the whole walk stays fast, and the only real price is the memory we spend storing the nodes.
Let us trace the cycle list first. The nodes are A to G with values 3, 2, 0, 4, 7, 1, and 9, and node G loops back to node C. We store nodes by identity, so the table tracks node names rather than values.
| step | current node | already in set? | set after this step |
|---|---|---|---|
| 1 | A (val 3) | no | {A} |
| 2 | B (val 2) | no | {A, B} |
| 3 | C (val 0) | no | {A, B, C} |
| 4 | D (val 4) | no | {A, B, C, D} |
| 5 | E (val 7) | no | {A, B, C, D, E} |
| 6 | F (val 1) | no | {A, B, C, D, E, F} |
| 7 | G (val 9) | no | {A, B, C, D, E, F, G} |
| 8 | C (val 0) | yes → return true | {A, B, C, D, E, F, G} |
Now the clean list, same values but node G points to null. The set fills up in the very same way, yet the ending changes.
| step | current node | already in set? | set after this step |
|---|---|---|---|
| 1 | A (val 3) | no | {A} |
| 2 | B (val 2) | no | {A, B} |
| 3 | C (val 0) | no | {A, B, C} |
| 4 | D (val 4) | no | {A, B, C, D} |
| 5 | E (val 7) | no | {A, B, C, D, E} |
| 6 | F (val 1) | no | {A, B, C, D, E, F} |
| 7 | G (val 9) | no | {A, B, C, D, E, F, G} |
| 8 | null | loop stops → return false | {A, B, C, D, E, F, G} |
The cycle list, step by step.
We begin at node A while the set is empty. At step 1, node A is new, so we add it and move to B. Through steps 2 to 7, each node from B to G is fresh, so each one gets added and the walk moves on. By step 7 the set holds all seven distinct nodes, A through G. Then step 8 lands on node C again, because G pointed back to C. The set already holds node C from step 3, so the membership check returns true and we stop. Notice we matched the node object, not the value 0, and that identity match is the whole trick here.
The clean list, step by step.
The first seven steps look identical, because the nodes stay the same up to G. Steps 1 to 7 add nodes A to G one by one, just like before. During step 8, current follows G.next, which is null this time. Since current is now null, the while loop stops and we return false. No node ever repeated, so the set never reported a hit, and that clean null end is what separates this run from the cycle run.
| 💡 Interview Insight A common question is why we store nodes instead of values. Say it plainly: two nodes can share a value, so only the node object proves you have truly stood on that spot before. |
This approach is easy to reason about. The memory cost is the catch, as a long list fills a large set. Floyd’s method fixes exactly that, and we turn to it next.
Floyd’s method drops the set completely. Keep two pointers instead, a slow one and a fast one. The slow pointer steps one node per turn. Meanwhile the fast pointer jumps two nodes per turn. If the list loops, the fast pointer eventually meets the slow one inside the loop. If the list ends, the fast pointer reaches null first.
slow = head
fast = head
while fast is not null and fast.next is not null:
slow = slow.next
fast = fast.next.next
if slow == fast:
return true
return falsePicture a slow walker and a fast runner starting together at the head. The walker takes one step per turn, while the runner takes two. We repeat this until something clear tells us to stop.
fast and fast.next both exist, so the two-step jump never falls off the end.What happens when there is no loop? Then the runner keeps pulling ahead and finally reaches null. The moment fast or fast.next is null, the loop condition fails and we return false. A straight list can never make the two meet, so false is always the right answer there.
public class LinkedListCycleFloyd {
public static 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;
}
}The code is short because the two pointers carry the whole idea. The while condition is the key guard, and it protects the double jump from ever touching a null.
slow and fast on the head, so they start side by side.fast != null && fast.next != null before every turn. Without this guard, fast.next.next could hit a null and crash.slow ahead by one node.fast ahead by two nodes in a single step.==, which asks if both point at the exact same node object.Notice how the guard and the jump work together. The guard runs first and promises two more nodes exist. Only then does fast dare to leap two steps. That pairing is the reason the code never throws a null pointer error.
We trace the cycle list again, the same A to G with G looping back to C. Both pointers begin on node A. Each row shows where they land after one full turn of the loop.
Legend: slow moves 1 node per turn, and fast moves 2 nodes per turn.
| turn | slow lands on | fast lands on | same node? |
|---|---|---|---|
| 1 | B (val 2) | C (val 0) | no |
| 2 | C (val 0) | E (val 7) | no |
| 3 | D (val 4) | G (val 9) | no |
| 4 | E (val 7) | D (val 4) | no |
| 5 | F (val 1) | F (val 1) | yes → return true |
Now the clean list. Node G points to null this time, so the fast pointer soon runs out of room.
| turn | slow lands on | fast lands on | same node? |
|---|---|---|---|
| 1 | B (val 2) | C (val 0) | no |
| 2 | C (val 0) | E (val 7) | no |
| 3 | D (val 4) | G (val 9) | no |
| 4 (check) | — loop ends | fast.next is null | return false |
The cycle list, turn by turn.
Both pointers sit on node A before the loop starts. Turn 1 sends slow once from A to B. Fast jumps twice, from A to B to C, so the two differ and we go on. On turn 2, slow moves B to C, while fast jumps C to D to E, still landing on different nodes. Next comes turn 3, where slow moves C to D and fast jumps E to F to G, with no match yet. By turn 4, slow moves D to E. Fast jumps G to C to D, because G loops back to C, so they miss once more. Finally turn 5 sends slow from E to F. Fast jumps D to E to F, so both land on F and we return true.
Watch how the fast pointer kept circling once it entered the loop, gaining one node on slow each turn. That steady gain is why the two are guaranteed to meet.
The clean list, turn by turn.
The first three turns move exactly as before, since the nodes match up to G, so slow reaches D and fast reaches G. On turn 4, the loop condition runs again, and fast now sits on G, whose next is null on the clean list. Because fast.next fails the test, the loop ends at once and we return false. No meeting ever happened, so the answer is false, and the fast pointer found the real end that only a cycle free list can offer.
| 💡 Interview Insight Interviewers love to ask why fast and slow must meet. Keep it simple: inside a loop the fast pointer closes the gap by one node every turn, so the distance shrinks to zero and they collide. |
This is the answer interviewers hope to see. It keeps the same linear time as the set, yet the memory drops to a tiny constant.
Both methods return the same answer. They simply pay different prices in memory.
| Approach | Time | Space | Note |
|---|---|---|---|
| HashSet of nodes | O(n) | O(n) | Simple, but stores every node |
| Floyd’s two pointers | O(n) | O(1) | Fast and lean, the expected answer |
The time is linear for both. The real split is memory. A HashSet can swell to the size of the list, while Floyd’s needs only two pointers. So in an interview, mention the set first to show the idea, then switch to Floyd’s for the clean constant space finish.
| 💡 Interview Insight If asked which to use in real code, pick Floyd’s for its tiny memory. The set version is still fine for a quick first solution, or when node identity feels messy. |
A few small slips catch people on this problem, so keep them in mind before you submit.
fast.next check makes fast.next.next crash with a null pointer error.Run the empty list and both single node cases through your code before you call it done. Those small inputs catch more bugs than a long list ever will.
A: Floyd’s Tortoise and Hare is the best choice. It runs two pointers, a slow one that moves one node per turn and a fast one that moves two. They meet inside a loop, and the method needs only O(1) extra space.
A: Once both pointers enter the loop, the fast pointer gains one node on the slow pointer every turn. The gap keeps shrinking by one until it reaches zero, so the two land on the same node.
A: Both the HashSet and Floyd’s methods run in O(n) time. The HashSet uses O(n) space because it can store every node, while Floyd’s uses O(1) space with just two pointers.
A: Compare node objects, not values. Two different nodes can hold the same value, so only the node identity proves the walk returned to a spot it already visited.
A: An empty list has no cycle, so the answer is false. A single node is a cycle only when it points to itself; if it points to null, the answer is false.
Linked List Cycle in Java looks small, yet it teaches a habit you reuse everywhere. When a plain walk might run forever, you need a reliable way to catch the loop.
Our seven node traces showed both fixes clearly. The HashSet remembered every node and caught the repeat by identity. Floyd’s pointers raced at two speeds and collided inside the loop.
So take the pattern, not just the code. Use a set when memory is cheap and the logic must stay obvious. Reach for Floyd’s two pointers when you want linear time with almost no extra space.
That fast and slow pointer idea returns in many list problems. Learn it well right here, and the harder ones further down the list feel far less scary.