Quick revision
The short answer
Removing a loop from a linked list is a fast and slow pointer problem in three phases. A slow pointer moving one node and a fast one moving two meet only if there is a loop; a pointer from the head and one from the meeting point, moving one node each, then meet at the loop's first node; and one walk round the loop finds its last node, whose next we set to null. That is O(n) time and O(1) extra space.
The solution
What it costs
| Approach | Time | Extra space | Changes other nodes? |
|---|---|---|---|
| Hash set of visited nodes with prev | O(n) | O(n) | no |
| Mark visited nodes by changing values | O(n) | O(1) | yes, the values must be restored |
| Floyd: detect, find start, find last, cut | O(n) | O(1) | no |
What to remember
We removed a loop from a linked list, the footpath that runs onto a running track. The hash set brute force works but remembers every node. Floyd's method uses a few references: slow and fast meet inside the loop, a pointer from the head and one from the meeting point meet at the loop start because a + b is whole laps, and one walk round the loop finds the last node, whose next we set to null. That is O(n) time and O(1) space. The clue to remember is a linked list that may loop together with a demand for constant memory: two pointers at different speeds.
1What a loop in a linked list looks like, drawn as a path into a running track
Picture a park with a footpath that leads onto a circular running track. Walk along the path and onto the track, and you never reach an end. A singly linked list with a loop is exactly this. A linked list is a chain of nodes, where each node holds a value and a reference called next, which says which node comes after it. Normally the last node's next is null, meaning nothing, and a walk ends there. In a list with a loop, some node's next points back to an earlier node, so the walk never meets null.
Our example is 1 -> 2 -> 3 -> 4 -> 5 -> 6, where node 6 points back to node 3. Nodes 1 and 2 are the footpath, and nodes 3, 4, 5 and 6 are the track. Node 3, where the path joins the track, is called the start of the loop. Node 6, the last node on the track before we come back to the start, is the loop's last node.
Removing the loop means setting that last node's next to null. No node is deleted and no value moves, so the whole problem is to find one node, node 6, and change one reference, which is much smaller than it sounds.
Let us do it by hand. Put a finger on node 1 and follow the arrows, writing down each node: 1, 2, 3, 4, 5, 6, and then 3 again. The first node we write twice is node 3, so that is the start, and the node we stood on just before it, node 6, is the last node. We cut 6's arrow and the list ends there.
Six nodes. Nodes 1 and 2 are the approach path; nodes 3, 4, 5 and 6 are the track, closed by the arrow from 6 back to 3.
- loop start
- node 3
- loop's last
- node 6
- to cut
- 6.next
1Following the arrows from the head we pass 1, 2, 3, 4, 5 and 6, and the arrow from 6 takes us back to 3, so the walk never reaches null.
What to assume
- Must every node stay in the list?
- Yes, we only cut the one link that closes the loop.
- Can the loop close at the head, as in 1 -> 2 -> 3 -> 4 -> 1, or be one node pointing to itself?
- Yes.
- Do we compare nodes or values?
- Nodes, by reference, because two different nodes may hold the same value.
- How much extra memory may we use?
- The target is O(1), a fixed handful of variables. And we return true when we removed a loop and false when there was none.
A careful candidate asks a few questions first. Must every node stay in the list? Yes, we only cut the one link that closes the loop. Can the loop close at the head, as in 1 -> 2 -> 3 -> 4 -> 1, or be one node pointing to itself? Yes, and we will test both. Do we compare nodes or values? Nodes, by reference, because two different nodes may hold the same value. How much extra memory may we use? The target is O(1), a fixed handful of variables. And we return true when we removed a loop and false when there was none.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise the fast and slow pointer pattern
A beginner's first thought is to walk the list until it ends. That cannot work, because a list with a loop never ends, and a walk that has not ended yet tells us nothing. We need a way to notice that we are going round in circles.
The first clue is the word loop, together with a linked list. Inside a loop, a walk keeps returning to nodes it has already visited. Whatever we do must notice a repeat.
The second clue is the expectation of constant memory, which interviewers state or expect. Remembering every node we pass would notice the repeat, but with only a few variables we must notice it without remembering the past.
The third clue is the word remove. Detection alone needs only a yes or no. Removal needs a position: the start of the loop, and the node just before it on the track. So we need a method that gives more than a yes or no.
These clues point to the linked lists family and to its most famous technique, fast and slow pointers, also called Floyd's cycle method after Robert Floyd. A pointer here is simply a variable that refers to a node, like a finger resting on it. Two pointers move through the same list at different speeds, slow one node per step and fast two. On the track, the faster runner must eventually catch the slower one from behind, which happens only if there is a track at all. The rule to carry to new problems is that two pointers at different speeds can find, with O(1) memory, whether a list loops, where the loop starts and how long it is.
Two other ideas fit less well. Reversing the list as we walk, or marking each visited node by changing its value, can reveal a loop, but both change the list in ways we would have to undo. A hash set of visited nodes is the honest first attempt, and we try it next.
3The honest first attempt, remembering every node
The most natural brute force is what we did by hand: write down every node we visit, and stop at the first one we have seen before. In Java the notebook is a HashSet, a collection that can tell us in about one step whether it already holds something. Its add method returns false when the item was already there, which is exactly the repeat we are looking for.
To remove the loop we also need the node we came from, because that node's arrow is the one that closes the loop. So we keep a second reference, prev, one node behind. When we arrive at a node already in the set, that node is the start of the loop, and prev is the last node of the loop. Setting prev.next = null removes it.
Let us run it by hand. The set receives nodes 1 to 6, with prev one step behind. Then 6's arrow leads to node 3, add reports that node 3 is already there, prev is node 6, and we cut 6.next.
Now let us count. On our example the walk took seven steps and the set grew to six nodes. For n nodes the walk takes about n steps, so the time is O(n), which is as good as we can hope for, since we must at least reach the loop. But the set holds every node, so the extra space is O(n) as well, a million entries for a million nodes.
Where is the waste? The set remembers the whole history of the walk, yet we only ever ask it two narrow questions: does the walk repeat, and where does it first repeat. So the question that leads us on is whether two pointers and a little counting can answer both questions without the notebook.
4Getting to three phases, one observation at a time
Phase 1 answers whether there is a loop. slow and fast start on the head, and each step slow moves one node and fast moves two. Without a loop, fast reaches the end and we return false. With one, both pointers end up on the track, and then they must meet.
Why must they meet, and why can fast not jump over slow? Think of the distance from fast forward to slow along the track. Each step slow moves one node away and fast moves two nodes closer, so the distance shrinks by exactly one. A number that shrinks by one each step cannot skip over 0, so it reaches 0, and at that moment both pointers stand on the same node. On our example they meet at node 5.
Phase 2 finds the start, the step that looks like magic until we count. Let a be the number of steps from the head to the loop start, b the steps from the loop start forward to the meeting point, and L the number of nodes in the loop. On our example a is 2, b is 2 and L is 4. When they meet, slow has walked a + b nodes, and fast, moving twice as fast for the same number of steps, has walked twice that. The extra a + b nodes that fast walked were spent going round the loop, so a + b is a whole number of laps.
a is the path from the head to the loop start, b runs from the loop start to the meeting point, and L is the length of the loop.
- a
- 2 (1 -> 2 -> 3)
- b
- 2 (3 -> 4 -> 5)
- L
- 4 (3, 4, 5, 6)
- slow walked
- a + b = 4
- fast walked
- 2(a + b) = 8
1Slow and fast meet at node 5. From the head to the loop start, node 3, is a = 2 steps. From node 3 on to node 5 is b = 2 steps. The loop has L = 4 nodes.
- from head
- 1 -> 2 -> 3
- from meet
- 5 -> 6 -> 3
- both take
- a = 2 steps
2Fast walked 4 more nodes than slow, exactly one lap. So a + b = L, and a = L - b = 2: two steps from node 5 also lead to node 3, by 5 -> 6 -> 3.
On our example that is exactly one lap, 4 nodes. Now read it as a walk. If we stand on the meeting point, which is b steps past the start, and walk a more steps, we have walked b + a steps from the start, a whole number of laps, so we are back on the start. A pointer walking a steps from the head also lands on the start, by the definition of a. So we put a new pointer, start, on the head, leave slow on the meeting point, and move both one node per step; they meet exactly at the loop's first node.
Phase 3 walks forward from the loop start to the node whose next is the start, node 6 here, and sets its next to null.
A beginner often asks why we do not simply cut at the meeting point with slow.next = null, since we are standing there. Let us try it. slow is on node 5, so 5.next becomes null, the list becomes 1, 2, 3, 4, 5, and node 6 is lost. The meeting point is just where the runners happened to meet, not the end of the loop.
A loop that closes at the head deserves a check. In 1 -> 2 -> 3 -> 4 -> 1, a is 0, so phase 2 starts with both pointers on node 1 and does not move, and phase 3 walks round to node 4 and cuts its arrow.
5Watching the three phases on the six-node example
The picture plays the program on 1 -> 2 -> 3 -> 4 -> 5 -> 6 with 6 pointing back to 3. The nodes never move. The arrow drawn from node 6 back to node 3 is the link that closes the loop. Under the nodes are the pointers, and the panel shows which phase we are in and where each pointer stands.
Watch the gap between fast and slow in phase 1, and then watch the two pointers in phase 2 arrive at node 3 from different directions.
The nodes never move. Watch the pointers under them: phase 1 detects the loop, phase 2 finds its start, phase 3 finds its last node and cuts.
- phase
- 1, detect
- slow
- node 1
- fast
- node 1
1Phase 1 begins. slow and fast both stand on the head, node 1. Each step, slow moves one node and fast moves two.
- phase
- 1, detect
- slow
- node 2
- fast
- node 3
2Step 1: slow moves to node 2 and fast jumps to node 3. Fast is already on the loop; slow is still on the approach path.
- phase
- 1, detect
- slow
- node 3
- fast
- node 5
3Step 2: slow reaches node 3, the loop start, and fast jumps to node 5. Both are now on the loop, two nodes apart.
- phase
- 1, detect
- slow
- node 4
- fast
- node 3
4Step 3: slow moves to node 4, and fast goes 6 then round to 3. Fast is now one node behind slow on the loop.
- phase
- 1, detect
- slow
- node 5
- fast
- node 5
- meet
- true
5Step 4: slow moves to node 5 and fast jumps 4 then 5. They stand on the same node, so there is a loop. They met at node 5.
- phase
- 2, find start
- start
- node 1
- slow
- node 5
6Phase 2 begins. A new pointer, start, goes to the head, while slow stays on the meeting point, node 5. Both will now move one node per step.
- phase
- 2, find start
- start
- node 2
- slow
- node 6
7Phase 2, step 1: start moves to node 2 and slow moves to node 6. They are not on the same node yet.
- phase
- 2, find start
- start
- node 3
- slow
- node 3
- steps
- 2 = a
8Phase 2, step 2: start moves to node 3, and slow follows 6's arrow back to node 3. They meet exactly at the first node of the loop.
- phase
- 3, find last
- last
- node 3
- last.next
- node 4
9Phase 3 begins. last starts on the loop start, node 3. We move it forward while its next is not the start.
- phase
- 3, find last
- last
- node 6
- last.next
- node 3 = start
10last moves 4, then 5, then 6. Node 6's next is node 3, the start, so node 6 is the last node of the loop.
- phase
- done
- 6.next
- null
- returned
- true
11
last.next= null cuts the arrow from 6 to 3. The list is now 1 -> 2 -> 3 -> 4 -> 5 -> 6, ending in null, and we return true.
Let us read the important frames back. In the third frame both pointers are on the track, with fast two nodes behind slow going forward. In the fourth frame that distance is one, and in the fifth it is zero, at node 5, exactly as the shrinking distance argument promised.
In phase 2, start comes along the footpath, 1 then 2 then 3, while slow goes round the track, 5 then 6 then 3. Both took a = 2 steps. That is the counting from the distance picture coming true on real nodes.
In phase 3, last walks from 3 until last.next is the start, at node 6, and the final frame shows its link box holding null.
6The complete Java program
Here is the whole program, with a small Node class, the removeLoop method, a build helper that makes a list of n nodes and links the tail back to node loopTo, and show to print a list. main tests a loop in the middle, a loop that closes at the head, a single node pointing to itself, and a list with no loop.
Let us read removeLoop in the order it runs. slow and fast start on the head, and meet starts false. The while condition, fast != null && fast.next != null, makes sure fast can safely take two steps, because fast.next.next would throw a NullPointerException if fast.next were null. Inside, slow moves one, fast moves two, and if they stand on the same node we set meet and break. The test slow == fast compares references, not values.
Without a meeting, fast reached the end, so we return false without touching the list. Otherwise phase 2 puts start on the head and moves start and slow together, one node each, until they are the same node, the loop start.
Phase 3 puts last on the start and moves it while last.next != start, so it stops on the node whose arrow points back to the start. last.next = null cuts that arrow, and we return true. For a loop that closes at the head, phase 2 does not move at all, and phase 3 still finds the tail. So main prints true [1 2 3 4 5 6], true [1 2 3 4], true [1] and false [1 2 3].
7How much it costs, and the cases at the edges
Let us count on the example first. Phase 1 took 4 steps, phase 2 took 2, and phase 3 took 3, nine moves in all for six nodes. In general, slow meets fast before it finishes its first lap, so phase 1 takes at most about a + L steps. Phase 2 takes a steps and phase 3 takes fewer than L. Each of these is at most n, the number of nodes, so the total time is O(n).
We use four references, slow, fast, start and last, plus one boolean, however long the list is, so the extra space is O(1), compared with O(n) for the hash set.
| Approach | Time | Extra space | Changes other nodes? |
|---|---|---|---|
| Hash set of visited nodes with prev | O(n) | O(n) | no |
| Mark visited nodes by changing values | O(n) | O(1) | yes, the values must be restored |
| Floyd: detect, find start, find last, cut | O(n) | O(1) | no |
The edge cases are worth tracing. An empty list makes fast null at once, so we return false, and a list without a loop returns false unchanged, as main shows with [1 2 3].
A single node pointing to itself is the smallest loop. fast.next is the node itself, so slow and fast both move onto it and meet at once. Phase 2 does nothing, since start is the head, which is the meeting point. Phase 3 checks last.next != start, which is false straight away, so last is the node itself and we set its next to null, printing true [1]. A loop that closes at the head works the same way, with a equal to 0.
8Follow-up questions
Can phase 3 be avoided?
Yes, when the loop does not close at the head. In phase 2 the pointer coming round the track reaches the start from the loop's last node. So instead of waiting until both pointers are the same node, we stop when their next references are the same node, and the pointer on the track is then the last node; we cut its next. When a is 0, both pointers begin on the start, so this shortcut does not apply, and we still need the lap. Keeping phase 3 separate handles both cases with one piece of code.
How would you find the length of the loop?
After slow and fast meet, keep one pointer still and move the other round the loop one node at a time, counting steps until it comes back to the same node. On our example, from node 5 it goes 6, 3, 4, 5, so the length is 4. Knowing L gives another way to find the start: put one pointer L nodes ahead of another at the head, move both one step at a time, and they meet at the start, because the front pointer is always exactly one lap ahead.
Why does fast move two nodes and not three?
With two, the distance between the pointers on the track shrinks by exactly one per step, so it cannot skip past zero and they must meet on slow's first lap. With three, it shrinks by two, so on some loops fast jumps straight past slow and they meet only on a later lap. Two keeps both the meeting and the counting in phase 2 simple.
9Conclusion
We removed a loop from a linked list, the footpath that runs onto a running track. The hash set brute force works but remembers every node. Floyd's method uses a few references: slow and fast meet inside the loop, a pointer from the head and one from the meeting point meet at the loop start because a + b is whole laps, and one walk round the loop finds the last node, whose next we set to null. That is O(n) time and O(1) space. The clue to remember is a linked list that may loop together with a demand for constant memory: two pointers at different speeds.
Open with
Let me confirm: I cut the link from the loop's last node back to its start, keep every node, compare by reference, and return whether I removed a loop.
Then, if they want more
A brute force walks with a hash set and a previous pointer; the first node seen twice is the loop start, and prev is the last node, so I set prev.next to null. That costs O(n) memory. For constant memory I use fast and slow pointers in three phases.
First, slow moves one node and fast two; if fast reaches null there is no loop, and otherwise they meet, because the gap shrinks by one each step.
Second, if a is the distance from the head to the loop start and b from the start to the meeting point, then slow walked a plus b and fast walked twice that, so a plus b is whole laps. A pointer from the head and one from the meeting point, each moving one node, therefore meet at the start.
Third, I walk from the start to the node whose next is the start and cut it. Each phase is linear, so it is O(n) time and O(1) space. A loop at the head, where a is zero, and a node pointing to itself both work.
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 47 times in that collection. How it is counted
- Official documentation
- StringBuilder (Java 21), 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 a loop in a linked list and remove it.": https://scrivio-interview-library.netlify.app/data-structures/solutions/detect-a-loop-in-a-linked-list-and-remove-it-aba9d3/