Skip to content
Craft

How to detect a cycle in a linked list

How to detect a cycle in a linked list: use two pointers at different speeds, or a hash set of visited nodes. This essay proves why the fast and slow pointers must meet, traces a 10-node example, and compares the costs.

How to detect a cycle in a linked list: walk two pointers, one moving one step and the other two, and report a cycle if they ever meet. If the fast pointer reaches null, the list is finite. This uses O(n) time and O(1) memory, whereas storing visited nodes in a hash set costs O(n) memory.

That is the answer most interviewers want, but the answer alone is cheap. Plenty of people can recite the two-pointer trick and then freeze when asked why it terminates, why the speed ratio is two, or how to find the node where the loop begins. This essay covers all of that, with one concrete list traced by hand so you can check the numbers yourself.

What is a cycle in a linked list, and why does it matter?

A cycle exists when following the next pointers from the head never reaches null, because some node points back to a node you have already visited. The practical consequence is that any loop that walks the list to the end will run forever.

It is a real bug, not only an interview puzzle. A corrupted free list in an allocator, a mistakenly re-linked node in an LRU cache, or a dependency graph stored as a chain can all produce one. The symptom is a hang with a core pinned at 100 percent, which is a miserable thing to debug without knowing the shape of the cause.

It helps to name the three quantities that describe any list with a cycle. Let mu be the number of nodes before the cycle begins (the tail), let lambda be the length of the cycle, and let n be the total node count, so n = mu + lambda. Everything below is arithmetic on those three numbers.

Here is the example I will reuse. Ten nodes, labelled 0 through 9, in order. Node 9 points back to node 3. So mu = 3 (nodes 0, 1, 2), lambda = 7 (nodes 3 through 9), and n = 10.

How does the hash set approach work?

You walk the list and record every node you visit in a set; if you ever reach a node already in the set, there is a cycle, and if you reach null, there is not. It is correct, obvious, and the first thing you should say out loud in an interview.

def has_cycle_set(head):
    seen = set()
    node = head
    while node:
        if node in seen:
            return True
        seen.add(node)
        node = node.next
    return False

On the example list, you insert nodes 0 through 9, which is ten insertions, and on the eleventh step you land on node 3 again and stop. Time is O(n) expected, because each set operation is O(1) on average. Memory is O(n): you store one entry per node.

How bad is O(n) memory? For a list of 1,000,000 nodes in Python, the set's hash table alone is around 32 MB, before counting the cost of hashing object references. For a list of 50 nodes it is irrelevant. This is the right place to be honest: for small inputs the set is perfectly fine, and it has one advantage the pointer trick lacks. It is nearly impossible to get wrong.

Notice that you must store nodes (or their identities), never their values. Two distinct nodes can hold the same value, and a list like 1, 2, 1, 2 with no cycle at all would be falsely flagged. I have seen this exact mistake in review more than once.

How does Floyd's tortoise and hare algorithm work?

Start two pointers at the head. Advance the slow pointer one node per step and the fast pointer two nodes per step. If the fast pointer falls off the end, there is no cycle; if the two ever point at the same node, there is one.

def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            return True
    return False

The loop condition checks both fast and fast.next because the body dereferences fast.next.next. Checking only fast crashes on lists of odd length. That one line is the most common source of bugs in this function.

Here is the trace on the ten-node example, listing the node each pointer occupies after each step. Slow just walks 0, 1, 2, 3, and so on. Fast walks 0, 2, 4, 6, 8, then 9 and 3 (the wrap), landing on 3.

  • After step 1: slow at 1, fast at 2.
  • After step 2: slow at 2, fast at 4.
  • After step 3: slow at 3, fast at 6.
  • After step 4: slow at 4, fast at 8.
  • After step 5: slow at 5, fast at 3 (it went 9, then back to 3).
  • After step 6: slow at 6, fast at 5.
  • After step 7: slow at 7, fast at 7. They meet.

Seven slow moves and fourteen fast moves, so 21 pointer advances in total, against ten insertions plus ten set lookups for the hash approach. The pointer version does more raw hops here, but it allocates exactly two references. At 1,000,000 nodes the memory gap is the whole story; at ten nodes nothing matters.

An analogy I find useful: imagine a paperback where the last line of each page says continue on page X, and one page sends you back to page 4. The hash set is a notebook where you write down every page number you have read. Floyd's method is two bookmarks. You advance one by a page and the other by two, and you never write anything down. If a bookmark falls off the end of the book, the book is finite. If the bookmarks end up on the same page, you have been going in circles. The notebook costs paper in proportion to the book; the bookmarks cost nothing.

Why must the fast and slow pointers meet if there is a cycle?

Once both pointers are inside the cycle, the fast pointer gains exactly one node per step on the slow one, so the gap between them, measured around the loop, shrinks by one each step until it hits zero. It cannot skip over zero, because the gap changes by exactly one.

Spell it out. The slow pointer enters the cycle after mu steps. By then the fast pointer has made 2 times mu steps and is already inside the loop, somewhere. Call the gap between them g, the number of steps fast is ahead of slow around the cycle, with g between 0 and lambda minus 1. Each step, slow advances 1 and fast advances 2, so the gap changes by 1. After at most lambda minus 1 more steps the gap is 0 and they stand on the same node.

Check against the example: mu = 3. When slow enters at node 3 after three steps, fast has made six moves and sits at node 6. Fast is 3 nodes ahead of slow (3 to 6). Wait, though: the gap that matters is how far fast is behind slow, going forward around the loop, which is lambda minus 3, or 4. Four more steps close it: the meeting happens at step 3 + 4 = 7. That matches the trace.

This also gives the running time. Slow takes fewer than mu + lambda steps, which is n, so the whole thing is O(n) time. Some authors say the algorithm is O(n) because the slow pointer never completes a full lap before the meeting, and that is exactly the argument: it needs at most mu + lambda minus 1 steps.

There is a subtle point about the speed ratio. Why two and not three? Any speed works only if the gap can actually reach zero. If fast moves 3 per step and slow moves 1, the gap changes by 2 per step. When lambda is even and the gap is odd, the gap goes through only odd values modulo lambda and never equals zero, so the pointers leapfrog each other forever. With a ratio of two, the gap changes by 1, which can reach every value. So two is not arbitrary: it is the smallest ratio that guarantees a meeting for every cycle length, and it is also the cheapest.

How do you find the node where the cycle starts?

After the pointers meet, reset one pointer to the head and leave the other at the meeting point, then move both one step at a time. They meet again exactly at the first node of the cycle.

def cycle_start(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            p = head
            while p is not slow:
                p = p.next
                slow = slow.next
            return p
    return None

In the example, the meeting point is node 7 and the head is node 0. Step one: 1 and 8. Step two: 2 and 9. Step three: 3 and 3. They collide at node 3, which is where node 9 points back, after exactly mu = 3 steps.

Why does it work? At the meeting, slow has taken t steps and fast has taken 2t, and the difference, t, must be a whole number of laps: t = k times lambda. Slow is therefore k laps past the point where it entered, plus it walked mu to get in, so its position is mu steps into the cycle plus a multiple of lambda. Put plainly, slow sits at a distance of lambda minus mu (mod lambda) ahead of the cycle entrance, so walking mu more steps lands it back on the entrance. A pointer from the head also needs exactly mu steps to get there. In the example, t = 7 = 1 times lambda, and the meeting node 7 is 4 steps past the entrance at 3; four steps plus three more is seven, one full lap, back to node 3. If you want the algebra spelled out with more cases, the page on the math behind Floyd's cycle detection goes through it, and the general technique is covered under fast and slow pointers.

Which cycle detection approach should you use?

Use Floyd's algorithm when memory matters or an interviewer asks for constant space, and use the hash set when you need the answer to be obviously correct or when you also need to know which nodes are in the loop. Here is how the options compare.

ApproachTimeExtra spaceTrade-off
Hash set of nodesO(n) expectedO(n)Simplest to write; about 32 MB at 1,000,000 nodes in Python; finds the entrance directly as the first repeated node
Floyd (tortoise and hare)O(n)O(1)Two references; needs the extra pass to find the entrance; easy to botch the null checks
Brent's variantO(n)O(1)Fast pointer moves in power-of-two bursts; usually fewer node visits, but harder to explain at a whiteboard
Mark visited nodes in placeO(n)O(1)Destroys or mutates the input; unsafe with shared structures or concurrent readers

My own default: write the hash set first in an interview, state its cost, then offer Floyd as the improvement. That order shows you know the baseline and the trade, and it gives you a correct answer on the board in 90 seconds even if the clever version goes sideways. Interviewers care less about the trick than about whether you can reason from a working solution to a better one.

In production code I would still reach for the set on small structures. A cycle check on a 200-node config chain does not deserve a proof. Floyd earns its place when the list is large, the check runs often, or you are working in a language where allocating a million-entry set is itself a performance problem.

What mistakes do people make when detecting cycles?

The common failures are null-pointer crashes, comparing values instead of node identity, and starting the pointers in a way that makes them meet at step zero. All three are cheap to avoid once you know them.

  • Dereferencing null. Always guard fast and fast.next. Test on an empty list, a one-node list, and a two-node list.
  • Comparing values. Use is (or pointer equality), not == on the payload. Duplicate values are normal.
  • Checking equality before moving. If both pointers start at the head and you test slow is fast at the top of the loop, you report a cycle on every list. Move first, then compare.
  • Forgetting the self-loop. A single node whose next is itself is a cycle with mu = 0 and lambda = 1. The algorithm handles it: after one step, both pointers are on that node.
  • Using the wrong reset for the entrance. Reset one pointer to the head, not to the node after the head, and advance both at the same speed in the second phase.

A good habit is to hand-trace a list shaped like mine, with a tail longer than 1 and a cycle length that is not a divisor of the tail. Any off-by-one in the entrance phase will show up in under ten steps.

Frequently asked questions

What is the time complexity of Floyd's cycle detection?

It is O(n) time and O(1) space. The slow pointer takes fewer than mu + lambda steps before the pointers meet, which is at most n, and the entrance-finding phase adds at most mu more steps.

Can you detect a cycle in a linked list without extra memory?

Yes. Floyd's algorithm uses only two pointers, regardless of list length. You could also mutate nodes to mark them as visited, but that damages the input and is a poor idea in shared or concurrent code.

Why does the fast pointer move two steps instead of three?

With a speed difference of one, the gap between pointers shrinks by exactly one per step and must hit zero. With a difference of two, a gap of odd size in a cycle of even length can never close, so the pointers may never land on the same node.

To practise the full version, including the entrance-finding pass, work through Linked List Cycle II.