← Back to Algorithms, page 2

algorithms-0040 · Medium fresher

Detect a cycle in a linked list and return the node where the cycle begins, using O(1) extra space.

Move a slow pointer one step and a fast pointer two steps. If fast reaches the end, there is no cycle; if they meet, there is one. To find the start, reset one pointer to the head and move both one step at a time; they meet at the cycle's first node. O(n) time and O(1) space, versus O(n) space for a visited set.

Full answer

Problem

Given the head of a singly linked list, return the node where a cycle begins, or None if there is no cycle. Do not modify the list.

Example: 3 -> 2 -> 0 -> -4, with -4 linking back to 2: return the node with value 2.

Constraints: 0 <= n <= 10^4 nodes. Return the node object, not its value (values may repeat).

Brute force

Store visited nodes in a set; the first node seen twice is the cycle start. O(n) time, O(n) space. The test uses this as the reference.

Optimal approach

  1. slow = fast = head.
  2. While fast and fast.next: slow = slow.next, fast = fast.next.next; if slow is fast, a cycle exists.
  3. Set slow = head; move slow and fast one step at a time until they meet; return that node.
  4. If the loop ends, return None.

Why it works

Detection: inside a cycle, the fast pointer gains one node per step on the slow pointer, so the gap closes and they must meet within one lap.

Finding the start: let a be the distance from head to the cycle start, b the distance from the start to the meeting point and L the cycle length. Fast has travelled twice as far as slow: 2(a + b) = a + b + kL for some whole number k, so a = kL - b. Starting from the meeting point, walking a steps is the same as walking kL - b steps, which lands exactly on the cycle start. A pointer from the head reaches the start after a steps too, so they meet there.

Complexity

O(n) time, O(1) extra space.

Code

python
class ListNode:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next


def detect_cycle(head):
    """Floyd's algorithm. Return the node where the cycle starts, or None. O(1) space."""
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:                 # they met inside the cycle
            slow = head
            while slow is not fast:      # move both one step: they meet at the start
                slow = slow.next
                fast = fast.next
            return slow
    return None


def detect_cycle_set(head):
    """Brute force with a set of visited nodes. O(n) extra space."""
    seen = set()
    while head:
        if head in seen:
            return head
        seen.add(head)
        head = head.next
    return None


def build(values, pos):
    """Build a list; the tail links to index pos (-1 for no cycle)."""
    nodes = [ListNode(v) for v in values]
    for a, b in zip(nodes, nodes[1:]):
        a.next = b
    if nodes and pos >= 0:
        nodes[-1].next = nodes[pos]
    return (nodes[0] if nodes else None), nodes


if __name__ == "__main__":
    for f in (detect_cycle, detect_cycle_set):
        head, nodes = build([3, 2, 0, -4], 1)
        assert f(head) is nodes[1]
        head, nodes = build([1, 2], 0)
        assert f(head) is nodes[0]
        head, nodes = build([1], -1)
        assert f(head) is None
        head, nodes = build([1], 0)              # node pointing to itself
        assert f(head) is nodes[0]
        assert f(None) is None
        for n in range(1, 12):                   # every list length and cycle start
            for pos in range(-1, n):
                head, nodes = build(list(range(n)), pos)
                assert f(head) is (nodes[pos] if pos >= 0 else None)
    print("all tests passed")

Save as a40_cycle.py and run python3 a40_cycle.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty list. One node with no cycle. One node pointing to itself. Cycle starting at the head. The test builds every length from 1 to 11 with every cycle start position. Compare nodes with is, not by value.

Pattern

Fast and slow pointers (Floyd's tortoise and hare). Also finds the middle of a list, checks a "happy number", and finds a duplicate number in an array of n + 1 values treated as a function graph.

python
class ListNode:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next


def detect_cycle(head):
    """Floyd's algorithm. Return the node where the cycle starts, or None. O(1) space."""
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:                 # they met inside the cycle
            slow = head
            while slow is not fast:      # move both one step: they meet at the start
                slow = slow.next
                fast = fast.next
            return slow
    return None


def detect_cycle_set(head):
    """Brute force with a set of visited nodes. O(n) extra space."""
    seen = set()
    while head:
        if head in seen:
            return head
        seen.add(head)
        head = head.next
    return None


def build(values, pos):
    """Build a list; the tail links to index pos (-1 for no cycle)."""
    nodes = [ListNode(v) for v in values]
    for a, b in zip(nodes, nodes[1:]):
        a.next = b
    if nodes and pos >= 0:
        nodes[-1].next = nodes[pos]
    return (nodes[0] if nodes else None), nodes


if __name__ == "__main__":
    for f in (detect_cycle, detect_cycle_set):
        head, nodes = build([3, 2, 0, -4], 1)
        assert f(head) is nodes[1]
        head, nodes = build([1, 2], 0)
        assert f(head) is nodes[0]
        head, nodes = build([1], -1)
        assert f(head) is None
        head, nodes = build([1], 0)              # node pointing to itself
        assert f(head) is nodes[0]
        assert f(None) is None
        for n in range(1, 12):                   # every list length and cycle start
            for pos in range(-1, n):
                head, nodes = build(list(range(n)), pos)
                assert f(head) is (nodes[pos] if pos >= 0 else None)
    print("all tests passed")

Floyd's algorithm with a visited-set reference; tests cover every list length 1 to 11 and every cycle position.

Complexity

Time: O(n). Space: O(1); the set version is O(n). The meeting-point argument a = kL - b explains the second phase.

By level

Fresher: Gives the set solution, then Floyd's detection with careful null checks. Should compare nodes by identity, not value.

Mid: Finds the cycle start and explains the distance equation clearly. Explains why the fast pointer cannot skip past the slow one without meeting it.

Senior: Applies the technique to function graphs such as finding duplicates, computes the cycle length, and compares with Brent's algorithm. Can explain how the method finds a duplicate in a list of n + 1 values.

Key points

  • Slow moves one step, fast moves two
  • Meeting means a cycle exists
  • Reset one pointer to head and move both one step
  • They meet at the cycle start because a = kL - b
  • O(1) extra space

Common mistakes

  • Checking fast.next.next without checking fast.next
  • Comparing values instead of node identity
  • Returning the meeting point as the cycle start
  • Modifying the list to mark visited nodes

Follow-ups

  • How would you find the cycle length?
  • How do you find the middle node in one pass?
  • How does this solve "find the duplicate number"?

Tips

  • Start with the visited-set solution
  • Explain why fast catches slow
  • Write the a + b distance equation

Evaluation rubric

  • Correct detection and start-finding
  • Correct null checks
  • Gives the distance argument
  • Correct complexity