Scrivio Interview library
Linked listsLinked listsReported 119 times · 15 min read · updated 15 November 2026

Detect whether a singly linked list contains a loop.

1What it means for a linked list to go round in circles

Think of a treasure hunt. You are handed the first note, and each note tells you where the next one is hidden. Normally the last note says there are no more notes, and the hunt is over. A singly linked list works exactly like this. Each note is a node, which holds a value, and the line telling you where to go next is a reference called next. The first node, the one we are handed, is called the head, and the last node's next refers to nothing, which Java writes as null.

Now imagine a hunt where someone made a mistake, and the sixth note sends you back to the place of the third note. You would walk to the third place, the fourth, the fifth, the sixth, the third again, and never be told to stop. That is a loop in a linked list: some node's next refers to a node we have already passed, so following next from the head never reaches null. We only have to answer yes or no: does this list contain a loop?

The question is smaller than it looks. We are not asked to repair the list or find where the loop begins; we only have to notice that we are walking in circles. The difficulty is that a walker standing on one node cannot see the shape of the list.

Let us keep one example for the whole article: six nodes holding 1 to 6, where node 6's next refers back to node 3. Walk it with a finger on the picture below. From node 1 you go to 2, 3, 4, 5 and 6, and the arrow from 6 takes you to 3 again, then 4, 5, 6, 3, for ever. So the answer is true. If node 6's next were null, the walk would stop after six nodes and the answer would be false.

PictureThe example list, where node 6 points back to node 3

Six nodes. The arrow leaving node 6 goes back to node 3, so nodes 3, 4, 5 and 6 form a circle.

  1. 123456head

    1Following the arrows from node 1 we pass 2, 3, 4, 5 and 6, and then the arrow from node 6 takes us back to node 3, so the walk never meets null.

What to assume

Do we compare nodes or the values inside them?
Nodes, because two different nodes may hold the same number, and a loop means reaching the same node twice.
Can the list be empty?
Yes, and it has no loop.
Can a single node point to itself?
Yes, and that is a loop of length one.
Do we return only true or false?
Yes.
May we change the list?
No, we leave it as it is.

A careful candidate asks a few questions first. Do we compare nodes or the values inside them? Nodes, because two different nodes may hold the same number, and a loop means reaching the same node twice. Can the list be empty? Yes, and it has no loop. Can a single node point to itself? Yes, and that is a loop of length one. Do we return only true or false? Yes; finding where the loop starts is a follow-up we answer at the end. May we change the list? No, we leave it as it is.

2How to recognise the fast and slow pointer pattern

A beginner reading this question usually thinks of walking the list until we reach null. On our example the walk never reaches null, so the program never stops. The next idea is to count: if we have taken more steps than there are nodes, we must have repeated one. But we do not know how many nodes there are, and counting them needs the very walk that might never end.

So let us read the question slowly and take its clues one at a time. The first clue is the word loop. The danger is a walk that never finishes, so whatever we do has to decide while we are still walking.

The second clue is singly linked. Each node knows only the node after it, so we cannot look backwards, jump ahead by an index, or ask for the length. All we can do is follow next with one or more fingers resting on nodes. A finger of this kind, a variable that refers to a node, is what we call a pointer.

The third clue always follows the question: can you do it without extra memory? Then we cannot write down every node we have visited. The only other tool is a second pointer, and two pointers on the same list can differ only in speed.

Together these clues point to the linked lists family, and to the technique called fast and slow pointers: two pointers walk the same list, a slow one moving one node per step and a fast one moving two. Go back to the treasure hunt. If two friends follow the same notes, one reading one note a minute and the other two, then on a hunt with an end the fast friend simply finishes first. But if the notes go round in a circle, the fast friend can never finish, and sooner or later comes up behind the slow friend. The rule to carry to new problems is this: whenever something follows a next step and you must find out whether it repeats, without remembering the past, try two pointers at speeds one and two.

Some techniques look similar but do not fit. Pointer rewiring, as in reversing a list, changes the next references, and here we must leave the list alone. A hash set of visited nodes works but costs memory, so it becomes our brute force. Graph cycle detection with depth first search is built for nodes with many outgoing edges; a list node has only one next, which is why two simple walkers are enough.

3The honest first attempt, remembering every node we visit

When we are worried about walking in circles, the natural defence is to mark every place we have been, like ticking off each note of the treasure hunt in a notebook. If we ever pick up a note we have already ticked, we know we have gone round. This is a perfectly good first attempt, and an interviewer is glad to hear it, because it is correct and easy to explain.

In Java the notebook is a HashSet, a collection that tells us very quickly whether it already contains something. We walk from the head and add each node to the set. The add method returns false when the node is already there, which is exactly the moment we have come back, so we return true. If we reach null, the list ended and we return false. By hand on the example, we add 1, 2, 3, 4, 5 and 6, each one new; then the arrow from node 6 brings us to node 3, add returns false, and we answer true.

Step throughThe hash set remembers every node it passes

The answer is right, but look at the set on the right: it ends up holding every node of the list.

  1. 123456n
    seen
    {1, 2, 3}
    set size
    3

    1We have stood on nodes 1, 2 and 3 and written each one into the set. None was there before, so we keep walking.

  2. 123456n
    seen
    {1, 2, 3, 4, 5, 6}
    set size
    6

    2After node 6 the set holds all six nodes. The memory we use has grown with every step of the walk.

  3. 123456n
    seen
    {1, 2, 3, 4, 5, 6}
    set size
    6
    answer
    true

    3The arrow from node 6 brings us to node 3, and add reports that node 3 is already in the set. We have been here before, so there is a loop.

Java
static boolean hasCycleWithSet(Node head) {
Set<Node> seen = new HashSet<>(); // every node we have stood on
for (Node n = head; n != null; n = n.next) {
if (!seen.add(n)) return true; // add says false: we were here before
}
return false; // we reached null, so the list ends
}

One detail deserves a moment. The set compares nodes by identity, asking whether two references point to the very same object, which is what we want. If we stored the values instead, a straight list such as 1 -> 2 -> 1 would look like a loop, a mistake beginners make surprisingly often.

Now let us count. On the example we stood on seven nodes, six new ones and one repeat, and each add costs a small constant time on average. For n nodes we visit at most n + 1, so the time grows in step with n, which we write as O(n). The trouble is memory. The set ends up holding every node, as the picture shows, so the extra space is also O(n): ten million entries for a list of ten million nodes.

4Getting from a set of every node to two pointers

So where is the waste? Look at the last frame of the picture above. The set remembers the whole history of the walk, every node in the order we met it, yet the only question we ever asked it was a single yes or no: have we been here before? We are paying for a full diary when all we need is one fact.

This is where the second friend from the treasure hunt helps. Instead of remembering where we have been, we send two pointers down the list from the head. We call them slow and fast. In each step, slow moves one node with slow = slow.next, and fast moves two nodes with fast = fast.next.next. After each step we ask one question: are slow and fast on the same node?

First think about a list with no loop. Fast is ahead and moves faster, so it reaches the end first. Before fast takes its two hops, we check that fast and fast.next are not null; if either is null the list has ended, and we return false after roughly n / 2 steps. This check is also what stops the program from crashing.

Now the question every beginner asks. On a circle, why must they ever land on the same node? Could fast not jump straight over slow, again and again? Let us look carefully. Once both pointers are inside the circle, measure the gap, the number of nodes fast still has to walk forward to reach slow. In one step slow moves one node away, which makes the gap one bigger, and fast moves two nodes closer, which makes it two smaller. So the gap shrinks by exactly one node in every step.

A number that goes down by exactly one each time cannot skip over zero. From 3 it goes to 2, 1 and 0, and at 0 both pointers are on the same node. This is why speeds one and two are the safe choice; with speeds one and three the gap would shrink by two, and from 3 it would go to 1 and then jump past zero.

How long can this take? Slow enters the circle within n steps. Once it is in, the gap is less than the length of the circle, at most n, and it shrinks by one per step, so they meet within about 2n steps, using just two references. One beginner trap is worth naming. We compare slow == fast, which asks whether the two references point to the same node object. Writing slow.val == fast.val would compare the numbers inside, and two different nodes holding the same number would fool us.

5Watching slow and fast on the six-node example

The picture below plays the loop on our example, with the names slow and fast written under their nodes. On the right you can follow where each stands and the gap, the number of nodes fast must still walk forward to reach slow. The gap only makes sense once slow is inside the circle of nodes 3 to 6.

The first step is shown slowly, one line of code per frame, so you can see that slow moves first and fast second. After that each frame shows a whole step.

Step throughSlow and fast on 1 -> 2 -> 3 -> 4 -> 5 -> 6, with 6 pointing back to 3

Slow moves one node per step and fast moves two. Watch the gap, the number of nodes fast must still walk to reach slow, fall by one each step.

  1. 123456slowfast
    slow
    node 1
    fast
    node 1
    gap
    slow not in loop

    1Both pointers start on the head, node 1. The loop test asks whether fast and fast.next exist, and they do, so we may take a step.

  2. 123456slowfast
    slow
    node 2
    fast
    node 1

    2Step 1, first line: slow = slow.next moves slow one node, from 1 to 2. Fast has not moved yet.

  3. 123456slowfast
    slow
    node 2
    fast
    node 3
    gap
    slow not in loop

    3Step 1, second line: fast = fast.next.next moves fast two nodes, from 1 to 3. Slow is on 2, fast is on 3, so they are not on the same node.

  4. 123456slowfast
    slow
    node 3
    fast
    node 5
    gap
    2 nodes

    4Step 2 moves slow to node 3, so it has just entered the circle. Fast goes 3 -> 4 -> 5. Going forward from 5, fast needs 2 nodes, 6 and 3, to reach slow.

  5. 123456slowfast
    slow
    node 4
    fast
    node 3
    gap
    1 node

    5Step 3 moves slow to node 4, while fast goes 5 -> 6 -> 3, round the circle. Fast is now just 1 node behind slow.

  6. 123456slowfast
    slow
    node 5
    fast
    node 5
    gap
    0 nodes

    6Step 4 moves slow to node 5 and fast goes 3 -> 4 -> 5. The gap has shrunk from 1 to 0, so both pointers stand on node 5.

  7. 123456slowfast
    slow
    node 5
    fast
    node 5
    gap
    0 nodes
    answer
    true

    7The test slow == fast is true, because both refer to the very same node object, so hasCycle returns true after four steps.

Let us read the important frames back. After step 2, slow has just arrived on node 3, the first node of the circle, and fast is on node 5, which must pass node 6 to reach node 3, so the gap is 2.

In step 3, fast hops 5 -> 6 -> 3, which carries it round the circle, while slow moves on to node 4. Fast is now directly behind slow, and the gap is 1. In step 4 slow moves to node 5 and fast hops 3 -> 4 -> 5, landing on the same node. The gap went 2, 1, 0, falling by one each step, exactly as the argument promised, and nobody jumped over anybody.

6The complete Java program

Here is the full program. It has a small Node class, the hasCycle method, and a helper called build that makes a list of n nodes and, when asked, links the last node back to an earlier one. The main method tries four lists: our example, the same six nodes without a loop, a single node pointing to itself, and an empty list. The comment on each line shows what it prints.

Java
public class DetectCycle {
static class Node {
int val;
Node next;
Node(int val) { this.val = val; }
}
// Floyd's tortoise and hare: true when following next ever repeats a node.
static boolean hasCycle(Node head) {
Node slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next; // one step
fast = fast.next.next; // two steps
if (slow == fast) return true; // same node object, not equal values
}
return false; // fast fell off the end: the list ends
}
// Builds 1..n and, when loopTo >= 1, links the tail back to node number loopTo.
static Node build(int n, int loopTo) {
Node dummy = new Node(0), tail = dummy, target = null;
for (int i = 1; i <= n; i++) {
tail.next = new Node(i);
tail = tail.next;
if (i == loopTo) target = tail;
}
if (target != null) tail.next = target;
return dummy.next;
}
public static void main(String[] args) {
System.out.println(hasCycle(build(6, 3))); // true (6 links back to 3)
System.out.println(hasCycle(build(6, 0))); // false
System.out.println(hasCycle(build(1, 1))); // true (a node pointing to itself)
System.out.println(hasCycle(null)); // false
}
}

Let us read hasCycle in the order it runs. Both slow and fast start on head; if head is null, both are null and the loop test fails at once.

The while condition, fast != null && fast.next != null, is read from left to right, and Java stops as soon as one part is false. So if fast is null, we never look at fast.next, which would throw a NullPointerException. These two checks are exactly the two ways a list without a loop can end under fast's feet: fast lands on null, or fast lands on the last node, whose next is null.

Inside the loop, slow = slow.next takes one step; slow needs no null check, because it is behind fast and fast has already shown that the next two nodes exist. Then fast = fast.next.next takes two steps, and we compare the references. If they are the same node, we return true at once.

If the loop ever ends, fast ran out of list, so we return false. The build helper remembers the node numbered loopTo and links the tail back to it, which is how main makes our example, so the first line prints true.

7How much it costs, and the cases at the edges

Let us count on the example first. The loop ran four times, each step a few reference moves and one comparison. In general slow reaches the circle within n steps and fast catches it within one more trip round, so the time is O(n). Without a loop, fast walks off the end after about n / 2 steps, also O(n).

Whether the list has six nodes or six million, we hold the same two references, so the extra space is O(1), read as constant. The hash set held one entry per node, O(n).

Comparing the two ways to detect a loop
ApproachTimeExtra spaceChanges the list?
Hash set of visited nodesO(n)O(n)no
Slow and fast pointersO(n)O(1)no

The edge cases are all handled by the loop condition, without any extra code. For an empty list, fast is null at the start, so the loop never runs and we return false. For a single node with no loop, fast.next is null, so again we return false at once.

A single node whose next refers to itself is a loop of length one: slow moves onto the same node, fast moves two steps round and lands there too, and slow == fast is true after one step. A loop that closes at the head is found like any other, because the shrinking gap never cared where the circle begins.

8Follow-up questions

How do you find the node where the loop starts?

Let the two pointers meet as before. Then move one of them back to the head, leave the other on the meeting node, and move both one node per step. They meet again on the first node of the loop, because the distance from the head to the loop start equals the distance from the meeting node forward to the loop start, plus some whole trips round the circle. On our example they met on node 5; one pointer walks 1, 2, 3 and the other 6, 3, so they meet on node 3. It is still O(n) time and O(1) space.

How would you find the length of the loop?

Once slow and fast stand on the same node, that node is inside the circle. Keep one pointer there and walk the other forward, counting, until it comes back. On our example, from node 5 we pass 6, 3, 4 and return to 5, so the length is 4. It costs at most one extra trip round, so it stays O(n) time and O(1) space.

Why move fast by two and not by three or more?

With speeds one and two, the gap inside the circle shrinks by exactly one each step, so it must pass through zero. With speeds one and three it shrinks by two, and it can step from 1 straight past zero, so fast may jump over slow several times before they land together. Speeds one and two give the simplest proof, which is why everyone uses them.

9Conclusion

We detected a loop in a singly linked list. The hash set remembers every node and notices when one comes back, which is correct but keeps O(n) memory for a single yes or no. The fast and slow pointers move one node and two nodes per step; if the list ends, fast reaches null, and if it loops, the gap falls by one per step until they meet. That is O(n) time and O(1) space. The clue to remember is a walk along next references that might never end: to find out whether something repeats without remembering the past, use two pointers at different speeds.

What to say in the interviewAbout 90 seconds aloud

Open with

Let me confirm what is asked: return true if following next from the head ever reaches the same node twice, comparing node references, not values; the list may be empty or a node may point to itself.

Then, if they want more

A first approach adds every node to a hash set and reports a loop when add finds a node already there. That is O(n) time but O(n) memory for a yes or no answer. To use constant space I would use fast and slow pointers.

Both start at the head; each step slow moves one node and fast moves two, and then I check whether they are the same node. If the list ends, fast reaches null or a node whose next is null, and I return false; checking fast and fast.next first means I never dereference null.

If there is a loop, both end up inside it and the gap from fast to slow shrinks by exactly one node per step, so it reaches zero and they meet, and I return true. Slow enters the loop within n steps and fast catches it within one lap, so it is O(n) time and O(1) space.

If you want the start of the loop, I reset one pointer to the head and move both by one until they meet.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 119 times in that collection. How it is counted
Official documentation
java.util, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Detect whether a singly linked list contains a loop.": https://scrivio-interview-library.netlify.app/data-structures/solutions/detect-whether-a-singly-linked-list-contains-a-loop-b60211/

More linked lists questions