Linked List Cycle solution explained

Linked List Cycle is solved with Floyd's tortoise and hare: move one pointer one node at a time and another two nodes at a time, and if the list loops back on itself the fast pointer eventually lands on the slow one; if the fast pointer reaches the end, there is no loop. It runs in O(n) time with O(1) extra memory, beating the O(n) memory of a visited set.

By Published 8 min read

Understanding the question

You get the first node of a singly linked list. Normally, following the next references would end at a node that points at nothing. In a broken list, the last node points back at some earlier node instead, so the walk never ends. Report whether that happens. You do not know the length in advance, and you are not told where the loop would join; you only have the head.

Lists built for this page
ShapeHas a loop?Why
4 → 7 → 2 → 9, and 9 links back to 2yesAfter 9 the walk returns to 2 and repeats 2, 9 forever
5 → 1 → 8, and 8 links to nothingnoThe walk ends after three nodes
A single node that links to itselfyesThe smallest possible loop
(empty)noThere is nothing to walk
Lists built for this page. Scroll sideways on a small screen.

Good clarifying questions: may you modify the nodes, for example by marking them? Is there a memory limit? Do you only need a yes or no, or the node where the loop starts? The memory question is the one that moves you from the set-based answer to the two-pointer one.

What the interviewer is looking for

The hash set answer is expected within a minute. The real question is whether you know, or can reason your way to, a method that uses constant memory. Floyd's algorithm is famous enough that reciting it earns little; explaining why the fast pointer cannot jump over the slow one forever earns a lot. Strong candidates can also extend it to find where the loop begins, which takes a short distance argument most people never stop to understand.

Follow-ups worth preparing

  • Where does the loop begin? After the pointers meet, move one back to the head and advance both one step at a time. They meet again at the loop's first node. Code and the reasoning are below.
  • How long is the loop? From the meeting point, keep one pointer still and walk the other until it comes back, counting steps.
  • Find the repeated number in an array of n + 1 values drawn from 1 to n. Treat each value as a link to that index. A repeated value means two links point at one index, which is a loop, so Floyd's method finds the repeat in O(1) extra memory.
  • Why step by two and not three? With speeds of 1 and 2, the gap inside the loop shrinks by exactly one each step, so the fast pointer cannot skip past. Other speed pairs work too, but the argument is less tidy.
  • Can you do it by marking nodes? Yes, by changing each visited node's value or link, but that damages the list, so most interviewers rule it out.

First approach: remember every node you visit

Walk from the head and put each node, by identity rather than by value, into a hash set. If you ever reach a node already in the set, the list loops. If you reach the end, it does not. Two different nodes can hold the same value, which is why the set must store node references, not values. Time is O(n) and memory is O(n).

class Item:
    def __init__(self, key):
        self.key = key
        self.next = None


def loops_with_set(head):
    visited = set()
    node = head
    while node is not None:
        if node in visited:  # objects hash by identity by default
            return True
        visited.add(node)
        node = node.next
    return False
Node class used below, plus detection with a set of visited nodes.

Optimal approach: Floyd's slow and fast pointers

Start two pointers at the head. Each round, move slow one node and fast two nodes. If there is no loop, fast reaches the end first, and you return false; check that fast and fast.next both exist before taking the double step. If there is a loop, both pointers end up inside it. From then on, fast closes the gap to slow by one node every round, and a gap that shrinks by one each round must hit zero. When they point at the same node, return true.

How many rounds can this take? Slow enters the loop after at most n steps, and once both are inside, fast needs fewer rounds than the loop has nodes to catch up. So the total is O(n), and the only memory used is two references.

def loops(head):
    slow = fast = head
    while fast is not None and fast.next is not None:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            return True
    return False
Python: Floyd's cycle detection, O(n) time and O(1) extra space.
struct Item {
    int key;
    Item* next;
};

bool loops(const Item* head) {
    const Item* slow = head;
    const Item* fast = head;
    while (fast != nullptr && fast->next != nullptr) {
        slow = slow->next;
        fast = fast->next->next;
        if (slow == fast) return true;
    }
    return false;
}
C++17: the same two pointers. Comparing pointers compares node identity.

Comparing after moving, not before, matters: both pointers start on the head, so a check before the first move would report a loop in every list.

Follow-up: find where the loop starts

Call the distance from the head to the loop's first node a, and say the pointers meet b nodes into the loop, which has length L. When they meet, fast has walked twice as far as slow, and the extra distance is a whole number of laps. Working that through gives a = (a whole number of laps) minus b. In plain terms, walking a steps from the meeting point lands exactly on the loop's first node, and so does walking a steps from the head. So reset one pointer to the head and step both by one; they meet at the start.

def loop_entry(head):
    slow = fast = head
    while fast is not None and fast.next is not None:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            seeker = head
            while seeker is not slow:
                seeker = seeker.next
                slow = slow.next
            return seeker
    return None
Return the first node of the loop, or None if the list ends.

Complexity

Detection and its follow-ups
ApproachTimeExtra spaceNotes
Set of visited nodesO(n)O(n)Also finds the loop start directly: the first repeated node
Floyd's slow and fast pointersO(n)O(1)The expected answer
Floyd's plus a second walk for the startO(n)O(1)Standard follow-up
Marking visited nodesO(n)O(1)Destroys the input, usually not allowed
Detection and its follow-ups. Scroll sideways on a small screen.

Cases to test

  • Empty list and a single node without a loop: both return false.
  • A single node that points at itself: true, and the loop starts at the head.
  • A loop that joins at the head, so the whole list is a ring.
  • A loop that joins at the last node, so the tail points at itself.
  • A long straight lead-in followed by a short loop, and a short lead-in followed by a long loop.
  • Lists with repeated values but no loop, to make sure you compare nodes, not values.

Frequent mistakes

  • Checking only fast before the double step, then crashing on fast.next.next when fast.next is empty.
  • Comparing the pointers before moving them, which is true at the start.
  • Storing values in the visited set instead of nodes, which reports loops in lists that merely repeat a value.
  • Starting fast one step ahead and then getting the loop-start math wrong, since the distance argument assumes both start together.
  • Reciting the algorithm without the reason it terminates. Interviewers often ask for exactly that.

How to explain it out loud

Fictional example

Explaining why the fast pointer must catch up
Candidate
A set of visited nodes works in linear time and memory. To get constant memory, I use two pointers from the head, one moving one step and one moving two.
Candidate
If there is no loop, the fast one hits the end. If there is, both end up inside it, and every round the fast one gains exactly one node, so the gap shrinks to zero and they meet. That is linear time.
Candidate
On 4, 7, 2, 9 with 9 linking back to 2, slow moves to 7 and then 2, while fast moves to 2 and then around through 9 to 2 again, so they meet at 2 on the second round.

Keep practicing with these

Reverse Linked List and Merge Two Sorted Lists round out the core linked list skills, and the slow and fast pointers you learned here are what split a list in half for merge sort. The visited-set approach is the same membership check that solves Contains Duplicate. Visiting each node once to avoid going in circles is also the reason Number of Islands marks cells as seen. See all of them on the coding problems hub.

Practice support from Natively

List problems are often drawn as boxes and arrows, so a picture is the natural way in. During practice on Mac or Windows, Natively can read such a diagram or problem statement from a screenshot and suggest the two-pointer approach with code, plus the loop-start follow-up to prepare. With a mock round transcribed, you can review afterward whether your termination argument was clear. Read more about the AI assistant for coding interviews.

Questions people ask

How do you detect a cycle in a linked list?

Move a slow pointer one node and a fast pointer two nodes per round. If fast reaches the end, there is no cycle; if the two ever point at the same node, there is one. It is O(n) time and O(1) space.

Why does Floyd's algorithm always find the cycle?

Once both pointers are inside the loop, the fast one gains exactly one node per round, so the gap between them shrinks by one each time and must reach zero within one lap.

How do you find the node where the cycle begins?

After the pointers meet, move one of them back to the head and advance both one step at a time. The distance math works out so they meet again exactly at the first node of the loop.

Can you use a hash set instead?

Yes. Store each visited node by identity and stop when one repeats. It is O(n) time but also O(n) memory, which is why interviewers usually ask for the two-pointer version next.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP