Skip to main content
21

Linked List Cycle

Easylinked listfast & slow pointers

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Linked ListRead the beginner guide

Given the head of a linked list, return true if the list has a cycle, and false otherwise.

Understand the problem

In a normal linked list, following next pointers eventually reaches null: the end. A cycle means the last node's next points back to some earlier node instead, so following next goes round and round forever, like a race track.

Loading diagram...

Here -4 points back to 2, so the walk 3, 2, 0, -4, 2, 0, -4, 2, ... never ends.

In the tests, pos is the index of the node the tail links back to (-1 means no cycle). pos is only used to build the input: your function only receives head.

Example 1

text
Input:  head = [3, 2, 0, -4], pos = 1
Output: true

The tail (-4) links back to the node at index 1 (2), as in the picture above.

Example 2

text
Input:  head = [1, 2], pos = 0
Output: true

The tail (2) links back to the head (1).

Example 3

text
Input:  head = [1], pos = -1
Output: false

The single node's next is null, so the walk ends.

Constraints

  • 0 <= number of nodes <= 10^4

Note

Follow-up: a set of visited nodes works. Can you solve it with O(1) extra memory?

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Send a slow pointer (1 step at a time) and a fast pointer (2 steps at a time) down the list: if there's a cycle, the fast one catches up with the slow one; if not, the fast one reaches the end.

    The simple approach (and its cost)

    Walk the list and put every node you visit into a hash set. If you're about to visit a node that's already in the set, there's a cycle. If you reach null, there isn't.

    This is correct and a perfectly good first answer. Its cost is O(n) memory for the set. The follow-up asks for O(1).

    The key insight

    Picture two runners on a track:

    • If the track is a straight line, the faster runner simply reaches the end first.
    • If the track is a loop, the faster runner keeps going round and eventually comes up behind the slower one and catches them.

    In code, the runners are two pointers: slow moves 1 node per step, fast moves 2. This is called Floyd's cycle detection or the tortoise and hare.

    Why can't fast jump over slow? Once both are inside the loop, each step fast gains exactly one node on slow. So the gap between them shrinks 3, 2, 1, 0. It can't skip from 1 to -1. They must land on the same node.

    Step by step

    3 → 2 → 0 → -4, and -4 links back to 2:

    StepslowfastSame node?
    start33(skip the start)
    120no
    202no
    3-4-4yes ✅

    fast went 3 → 0 → 2 → -4 (two steps at a time, looping around). They met, so there's a cycle.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n). If there's no cycle, fast reaches the end in about n/2 steps. If there is one, once slow enters the loop, fast catches it within one lap.
    • Memory: O(1). Two pointers.

    Common mistakes

    • Only checking fast, not fast.next. fast.next.next crashes if fast.next is null. Check both.
    • Comparing values instead of nodes. Two different nodes can hold the same value ([1, 1] without a cycle). Compare the nodes themselves: slow === fast (or is in Python).
    • Checking slow === fast before moving. They both start at head, so they're equal immediately. Move first, then compare.

    Going deeper

    A famous follow-up: where does the cycle start? After they meet, put one pointer back at head and move both one step at a time. The node where they meet again is the start of the cycle. The same fast/slow trick also finds the middle of a list (when fast reaches the end, slow is halfway), which you'll use in Reorder List.

    Reference solution

    js
    /**
     * @param {ListNode | null} head
     * @return {boolean}
     */
    export default function hasCycle(head) {
      let slow = head // moves 1 node per step
      let fast = head // moves 2 nodes per step
      // If fast reaches the end, there's no loop. Check fast.next too, or fast.next.next crashes.
      while (fast && fast.next) {
        slow = slow.next
        fast = fast.next.next
        // Compare the NODES themselves (not their values). Meeting means fast lapped slow.
        if (slow === fast) return true
      }
      return false
    }
    ts
    export default function hasCycle(head: ListNode | null): boolean {
      let slow = head // moves 1 node per step
      let fast = head // moves 2 nodes per step
      // If fast reaches the end, there's no loop. Check fast.next too, or fast.next.next crashes.
      while (fast && fast.next) {
        slow = slow!.next
        fast = fast.next.next
        // Compare the NODES themselves (not their values). Meeting means fast lapped slow.
        if (slow === fast) return true
      }
      return false
    }
    python
    def has_cycle(head: ListNode | None) -> bool:
        slow = fast = head  # slow moves 1 node per step, fast moves 2
        # If fast reaches the end, there's no loop. Check fast.next too, or fast.next.next crashes.
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            # Compare the NODES themselves with `is` (not their values). Meeting means fast lapped slow.
            if slow is fast:
                return True
        return False