← Whiteboard questions

Linked List Cycle

Detect a list that loops back on itself

DSA, Easy, Linked List

Which structure or algorithm, and what does it cost.

A linked list may loop back on itself. The examples describe a list with values and link. The last node's next pointer goes to the node at position link (counting from 0), or to null when link is -1. Return true if you can follow next pointers from the first node forever, and false if you reach null. Your method may use only the first node and the next pointers, never link. Use only O(1) extra memory.

Examples

Input values = [3, 9, 4, 6], link = 1
Output True
Why the last node points back to the node holding 9, so the walk never ends.
Input values = [5, 5, 5], link = -1
Output False
Why the values repeat, but the nodes are different, and the last one points to null.
Input values = [8], link = 0
Output True
Why a single node that points to itself is a loop.

Constraints

Your answer must contain

Target Aim for O(n) time and O(1) extra memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

If the list ends, the walk reaches null. If it loops, the walk never does. How can you tell the two cases apart without walking forever?

Hint 2 the approach

You could remember every node you have seen. To use no memory, think of two walkers on the list moving at different speeds.

Hint 3 the key step

Move one pointer one step and another two steps at a time. If they meet, there is a loop. If the fast one reaches null, there is none.

Walkthrough

Full walkthrough brute force to best

Brute force

Walk from the first node and store every node you pass in a set. If you reach a node that is already in the set, there is a loop. If you reach null, there is none. This takes O(n) time but O(n) memory for the set.

Best method

Use two pointers that start on the first node. Move slow one node at a time and fast two nodes at a time. If the list ends, fast reaches null first and the answer is false. If there is a loop, both pointers end up inside it. Inside a loop, fast gains one node on slow at every step, so the gap between them shrinks by one each time, and they must land on the same node. When slow and fast are the same node, the answer is true. This needs no set, only two pointers.

Hand trace

Run on values [3, 9, 4, 6] with link 1. Name the nodes N0 to N3, and N3 points back to N1. Both pointers start on N0. Step 1: slow moves to N1, fast moves to N2. They differ. Step 2: slow moves to N2, fast moves two steps, N3 then N1, and is on N1. They differ. Step 3: slow moves to N3, fast moves two steps, N2 then N3, and is on N3. Both are on N3, so the answer is true.

Code

class Node:
    def __init__(self, val):
        self.val = val
        self.next = None
def has_cycle(values, link):
    nodes = [Node(v) for v in values]
    for i in range(len(nodes) - 1):
        nodes[i].next = nodes[i + 1]
    if nodes and link >= 0:
        nodes[-1].next = nodes[link]    # the last node links back to position link
    slow = fast = nodes[0] if nodes else None
    while fast and fast.next:
        slow = slow.next                # one step
        fast = fast.next.next           # two steps
        if slow is fast:
            return True
    return False

Time and memory

O(n) time: once both pointers are in the loop, they meet within one lap of it, and a lap has at most n nodes. O(1) extra memory: two pointers.

Common mistakes

  • Comparing values instead of nodes. Different nodes can hold the same value, as in [5, 5, 5].
  • Reading fast.next.next without checking fast.next first. On a list that ends, this reads past null.
  • Comparing slow and fast before the first move. Both start on the first node, so they are always equal at that point.

Related problems

More Linked List problems
Linked List Cycle: hints, walkthrough and Python solution