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

Detect whether a linked list contains a loop and, if it does, find the loop's length.

1What a loop in a linked list looks like, and what we must report

Picture a walking trail in a park, with arrows painted on the ground from one signpost to the next. On some trails the arrows end at a gate and you walk out. On others they lead you onto a circular track, and if you keep obeying them you go round for ever. A singly linked list is such a trail. Each node is a signpost holding a value and one arrow, a reference called next, which names the node after it. We are handed only the first node, the head, and a normal list ends at a node whose next is null, which is the gate.

A loop, also called a cycle, is the circular track: some node's next refers back to a node we already passed, instead of to null. We must say whether the list has a loop and, if it does, how many nodes are on the circle, the loop's length. It sounds frightening, because such a list never ends, but we only need to notice that we are going round, and then go round once more while counting.

Let us fix one example for the whole article. The list is 1 -> 2 -> 3 -> 4 -> 5 -> 6, but node 6 does not point to null. Its next refers back to node 3. If we walk from the head we visit 1, 2, 3, 4, 5, 6, then 3, 4, 5, 6 again, and so on for ever. The nodes 3, 4, 5 and 6 form the circle, so the answer is 4. Nodes 1 and 2 are the lead-in path before the circle; they do not count.

Do it once by hand. Put your finger on node 1 and follow the arrows, saying each value aloud. After six moves you say 3 again, and you notice only because you remember saying it before. A program has no such memory unless we give it one, and that is the problem to solve.

PictureThe example list, with node 6 pointing back to node 3

Nodes 1 and 2 lead in. Nodes 3, 4, 5 and 6 form the loop, because the arrow from node 6 bends back to node 3.

  1. 123456head
    loop nodes
    3, 4, 5, 6
    answer
    4

    1Walking from node 1 we pass 1, 2, 3, 4, 5, 6 and then return to 3. The four marked nodes form the loop, so the answer is 4.

What to assume

What do we return when there is no loop?
0, which can never be a real loop length.
Can the head be null?
Yes, and an empty list has no loop.
Can a node point to itself?
Yes, a loop of length 1.
Are values unique?
Not necessarily, so we compare nodes, not values.
May we change the list?
We assume not.

A careful candidate asks a few questions first. What do we return when there is no loop? 0, which can never be a real loop length. Can the head be null? Yes, and an empty list has no loop. Can a node point to itself? Yes, a loop of length 1. Are values unique? Not necessarily, so we compare nodes, not values. May we change the list? We assume not.

2How to spot the fast and slow pointer pattern

A beginner reading this question for the first time usually thinks of the simplest plan: walk the list, and stop when we reach null. That works perfectly for a list without a loop. With a loop, the walk never stops, so the program hangs. The next thought is to remember where we have been, as we did by hand, and that will be our honest first attempt. But the words of the question carry clues about a better way.

The first clue is the words linked list. We can only move forward, one next at a time. A looping list has no end to jump to, so whatever we learn, we must learn while walking forward.

The second clue is the word loop. A loop is a fact about the shape of the list, not about any single value. Questions about shape can often be answered by two walkers moving at different speeds, because the way their distance changes tells us about the shape they walk on. On a straight road the faster one simply pulls away. On a circle the faster one comes round from behind and catches up.

The third clue is what is not said. No extra storage is offered, and the list may be huge. Interviewers then usually look for constant extra memory, a fixed handful of variables whatever the size of the list.

These clues point to the linked lists family and to the technique called fast and slow pointers. A pointer, in Java, is a variable that refers to a node, like a finger resting on one signpost. The slow pointer moves one node per step and the fast pointer moves two; the idea is also called Floyd's cycle detection. The rule to carry to new problems is short. When a sequence can only be followed forward and you need to know whether it cycles or where its middle is, try two pointers at different speeds before reaching for extra memory.

Some patterns look similar but do not fit. A hash set of visited nodes also finds loops, and it is our brute force, but it costs memory for every node. Two pointers that start at both ends and move towards each other cannot work, because a looping list has no far end to start from.

3The honest first attempt, remembering every node we pass

When we did the example by hand, we noticed the loop because we remembered saying 3 before. The honest first attempt gives the program that memory, a notebook kept as a HashMap. It works like the index at the back of a book, telling us at once the position where we first met a node. Before writing a node down we look it up. If it is already there, we have come back to a node we passed, so we are on the loop.

The notebook also gives the length for free. Suppose we first met a node at position 2 and meet it again at position 6. Between those two visits we walked once round the circle and nothing else, so the circle has 6 - 2 = 4 nodes. That is why we store the position and not just a yes.

Step throughThe hash map grows by one entry for every node

The map remembers each node with the position where we first met it. It finds the answer, but it stores the whole list again.

  1. 123456cur
    index
    0
    map
    1:0

    1We stand on node 1 at index 0. It is not in the map yet, so we write it down as 1 at index 0 and move on.

  2. 123456cur
    index
    3
    map
    1:0 2:1 3:2 4:3

    2Three steps later we are on node 4 at index 3. Every node we passed is in the map, which already holds four entries.

  3. 123456cur
    index
    5
    map
    1:0 2:1 3:2 4:3 5:4 6:5

    3On node 6 at index 5 the map holds all six nodes. Its next arrow bends back to node 3, so the following step returns to a node we know.

  4. 123456cur
    index
    6
    map
    1:0 2:1 3:2 4:3 5:4 6:5
    first seen
    2
    answer
    6 - 2 = 4

    4At index 6 we are on node 3 again. The map says we first saw it at index 2, so the loop length is 6 - 2 = 4.

Java
static int loopLengthWithMap(Node head) {
Map<Node, Integer> position = new HashMap<>(); // node -> index where we first saw it
int index = 0;
for (Node cur = head; cur != null; cur = cur.next, index++) {
Integer first = position.get(cur);
if (first != null) return index - first; // seen before: the gap is the loop
position.put(cur, index);
}
return 0; // we reached null: no loop
}

Let us count the work on the example. We stand on nodes 1 to 6 at positions 0 to 5, writing each down, and at position 6 we meet node 3 again: seven steps, each a quick map lookup. For n nodes that is at most about n steps, so the time grows in step with n, which we write as O(n), read as order n. That part cannot really be beaten, because we must at least reach the loop.

The space is another matter. The map ends up holding an entry for every node, six here and n for n nodes, so the extra space is O(n). That is the waste: the map remembers the exact position of every node, when all we want to know is whether we are going round in circles.

So the beginner's question is natural. Can we notice that we are going round without writing anything down? On the park trail, could two people find out that the path is a circle without leaving marks on the ground? That is the question the next section answers.

4From the notebook to two walkers who must meet

Go back to the park. Two friends start together at the entrance; one walks, and one jogs at exactly twice the speed. If the trail ends at a gate, the jogger reaches it first and they never meet again, which proves there is no circle. If the trail leads onto a circular track, both end up on it, and the jogger eventually comes round from behind and draws level with the walker. Their meeting proves there is a circle.

In the list, the walker is the pointer slow and the jogger is the pointer fast. Both start at the head. Each step, slow = slow.next moves one node and fast = fast.next.next moves two. Before moving we check that fast and fast.next are not null, since fast would fall off the end first; if that fails, we return 0. After moving we ask whether slow == fast, which in Java asks whether they are the same node object.

Now the question every careful beginner asks. Fast moves two nodes at a time, so could it jump over slow again and again and never land on the same node? Look at the distance instead of the nodes. Once both are on the circle, count how many nodes fast must still walk forward to reach slow. In one step slow moves one node away and fast moves two nodes closer, so that distance shrinks by exactly one. A number that falls by exactly one each time cannot skip zero, and zero means both stand on the same node.

How long can that take? The distance is smaller than the circle, so they meet before slow finishes one lap of it, which keeps detection within O(n) steps although the list never ends.

The second half of the question is now easy. When they meet, slow stands on a node that is certainly on the circle. We leave slow there as a marker, start a third pointer, walker, on the node after it, and count its moves until it comes back to slow. A lap of a circle of L nodes takes exactly L moves, like tying a ribbon to one signpost and counting signposts until you see the ribbon again.

The most tempting mistake here is to count from the meeting node with a loop that checks walker != slow before walker has moved at all. If walker starts on slow, that test is false at once and the count is wrong. That is why our walker starts on slow.next with length already 1, so a node that points to itself is counted as a loop of length 1.

5Walking through the list with a loop at node 3

The picture plays the real program on our example. The nodes never move; the bent arrow from node 6 back to node 3 is the loop. Under the nodes you can see where slow and fast stand after each step, and the panel shows the distance fast still has to cover to reach slow once both are on the circle.

Watch that distance in the middle frames. It is the whole argument of the previous section, made visible: it goes 2, then 1, then 0. After the meeting, the pointer names change. slow stays put as our ribbon and walker goes round the circle while length counts.

Step throughSlow and fast meet inside the loop, then one lap counts it

Node 6 points back to node 3. First slow and fast race until they meet; then walker goes once round the loop while length counts the steps.

  1. 123456slowfast
    slow
    node 1
    fast
    node 1
    fast to slow
    not in loop
    length
    not counted

    1Both pointers start on the head, node 1. Nothing has moved yet, so there is no gap to measure and no length to count.

  2. 123456slowfast
    slow
    node 2
    fast
    node 3
    fast to slow
    not in loop
    length
    not counted

    2Step 1 moves slow one node to node 2 and fast two nodes to node 3. Fast is ahead, and neither pointer has seen a null.

  3. 123456slowfast
    slow
    node 3
    fast
    node 5
    fast to slow
    2
    length
    not counted

    3Step 2 moves slow to node 3, so slow has just entered the loop. Fast jumps from 3 over 4 to 5. Fast needs 2 more nodes to reach slow.

  4. 123456slowfast
    slow
    node 4
    fast
    node 3
    fast to slow
    1
    length
    not counted

    4Step 3 moves slow to node 4. Fast goes 5 -> 6 -> 3, round the bend and back into the loop, now 1 node behind slow.

  5. 123456slowfast
    slow
    node 5
    fast
    node 5
    fast to slow
    0
    length
    not counted

    5Step 4 moves slow to node 5 and fast from 3 over 4 to 5. Both are on the same node, so slow == fast is true and a loop exists.

  6. 123456slowwalker
    slow
    node 5
    walker
    node 6
    length
    1

    6Now we count. slow stays on node 5, walker starts on the node after it, node 6, and length starts at 1 for that one step.

  7. 123456slowwalker
    slow
    node 5
    walker
    node 3
    length
    2

    7walker follows the bent arrow from node 6 back to node 3, and length becomes 2. walker is not on slow yet, so we keep going.

  8. 123456slowwalker
    slow
    node 5
    walker
    node 4
    length
    3

    8walker moves to node 4 and length becomes 3. Node 4 is the last node of the loop before we arrive back at node 5.

  9. 123456slowwalker
    slow
    node 5
    walker
    node 5
    length
    4

    9walker steps onto node 5, where slow is waiting, so walker != slow is false and the loop ends. length is 4, and we return it.

Let us read the important frames back. In the third frame slow steps onto node 3 and enters the circle, and fast, on node 5, needs two more nodes to reach it. In the fourth, fast goes 5 -> 6 -> 3, round the bend, and comes up one node behind slow. In the fifth the distance is zero and both stand on node 5, so slow == fast is true.

Notice that they met on node 5, not on node 3 where the loop begins. That surprises many beginners, but any node on the circle is a good place for the ribbon, because a full lap from any of them takes the same number of steps.

The last four frames are the counting lap. walker starts on node 6 with length 1, follows the bent arrow to node 3, moves to node 4, and steps onto node 5 with length 4. walker is on slow, the inner loop stops, and we return 4, with no notebook at all.

6The complete Java program

Here is the whole program, with a small Node class, the loopLength method, and a build helper that makes the list 1 to n with the last node pointing back at a chosen node. main runs our example and four edge cases, and each comment shows what that line prints.

Java
public class LoopLength {
static class Node {
int val;
Node next;
Node(int val) { this.val = val; }
}
// Returns the number of nodes in the loop, or 0 when the list ends in null.
static int loopLength(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) { // same node object: we are inside a loop
int length = 1;
Node walker = slow.next;
while (walker != slow) { // go round once and count
walker = walker.next;
length++;
}
return length;
}
}
return 0; // fast fell off the end: no loop
}
// Builds 1..n and points the last node back to the node holding loopTo (0 means no loop).
static Node build(int n, int loopTo) {
Node head = new Node(1), tail = head, target = loopTo == 1 ? head : null;
for (int v = 2; v <= n; v++) {
tail.next = new Node(v);
tail = tail.next;
if (v == loopTo) target = tail;
}
tail.next = target;
return head;
}
public static void main(String[] args) {
System.out.println(loopLength(build(6, 3))); // 4
System.out.println(loopLength(build(5, 0))); // 0
System.out.println(loopLength(build(1, 1))); // 1
System.out.println(loopLength(build(4, 1))); // 4
System.out.println(loopLength(null)); // 0
}
}

Let us read loopLength in the order it runs. slow and fast both start on head. The while condition fast != null && fast.next != null is checked before every double jump, because fast would fall off the end first; if it fails, the list has a gate and we return 0. Java stops at the first false part, so fast.next is never asked for when fast is null.

Inside the loop slow takes one step and fast takes two, and only then do we compare them. The order matters. If we compared before moving, both would be on head at the very start and we would report a loop in every list.

When they meet, we are on the circle. length starts at 1 and walker on slow.next, counting the step from slow to the next node. The inner while moves walker and adds one until walker is back on slow, and we return that count.

The build helper points the last node at the node holding loopTo, or at null when loopTo is 0. So main prints 4, then 0, then 1 for the node pointing to itself, 4 for the list that loops back to its head, and 0 for the empty list.

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

Let us count on the example first. The race took four steps and the counting lap four more moves, eight in all on six nodes. In general slow walks the lead-in path and less than one lap before the meeting, at most n steps, and the lap is at most n more. Without a loop, fast reaches the end in about n / 2 steps. So the time is O(n) in every case.

The space is the good news. We keep three references, slow, fast and walker, and one counter, whether the list has six nodes or six million. That is O(1) extra space, read as constant, against O(n) for the notebook.

Comparing the two ways
ApproachTimeExtra spaceChanges the list?
HashMap of node to first positionO(n)O(n)no
Fast and slow pointers, then one lapO(n)O(1)no

The edge cases need no special code, and it is worth seeing why. For an empty list, fast is null, the while condition is false at once, and we return 0. For a single node with no loop, fast.next is null, so again we return 0.

A single node that points to itself is the smallest loop. In the first step both pointers land on that same node, so slow == fast at once; walker starts on slow.next, the same node, the inner loop never runs, and we return 1. A list whose last node points back to the head, as in build(4, 1), has no lead-in at all, and the lap counts all 4 nodes.

8Follow-up questions

How would you find the node where the loop starts?

After slow and fast meet, move one of them back to the head, leave the other on the meeting node, and move both one node at a time. Where they meet again is the first node of the loop. When they first met, fast had walked twice as far as slow, an extra whole number of laps, and that works out to mean the head is as far from the loop's start as the meeting node is, up to whole laps. On our example one pointer goes 1, 2, 3, the other 5, 6, 3, and they meet on node 3.

Why does fast move two nodes and not three?

With speeds one and two, the distance between the pointers on the circle shrinks by exactly one each step, so it cannot skip zero and they must meet within one lap. With speeds one and three, the distance shrinks by two each step, so on a circle of even length it could go 3, 1, then wrap past zero and keep missing, depending on where they start. Two is the simplest speed that is always safe.

9Conclusion

We found out whether a linked list loops, and how long the loop is, without remembering a single node. Slow moves one node and fast moves two; if fast reaches null the list ends, and if they stand on the same node there is a loop, because on the circle the distance between them shrinks by exactly one each step. One lap with a counter from the meeting node gives the length, in O(n) time and O(1) space. The clue to remember is a question about the shape of a list you can only walk forward: try two pointers at different speeds.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm the contract: I return the number of nodes in the loop, or zero if the list ends in null, and I compare node references, not values.

Then, if they want more

A simple approach keeps a HashMap from node to the position where I first saw it; meeting a node again, the difference in positions is the loop length. That is linear time but linear space. For constant space I use fast and slow pointers. Slow moves one node per step and fast moves two.

Before each move I check that fast and fast dot next are not null; if either is, I return zero. If slow and fast become the same node, there is a loop. They must meet, because on the circle fast closes the distance by exactly one node per step, so it reaches zero within one lap.

Then I start a walker at slow dot next with a count of one and move it until it returns to slow; the count is the length. That is O(n) time and O(1) space, and the empty list, a single node, and a self-loop all fall out of the null checks.

About this answer

Last updated
14 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 20 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 linked list contains a loop and, if it does, find the loop's length.": https://scrivio-interview-library.netlify.app/data-structures/solutions/detect-whether-a-linked-list-contains-a-loop-and-if-it-does-find-53833a/