LeetCode #141 Easy

Linked List Cycle

Linked List Cycle is LeetCode 141 (Easy). Given the head of a singly linked list, return true if following the next pointers ever brings you back to a node you have already passed, and false if the walk ends at null.

  • pos in the examples only says where the last node links back to; it is not passed to your function.
  • The list has up to 10⁴ nodes, and the follow-up asks for O(1) extra memory.
Constraints
  • The number of the nodes in the list is in the range [0, 10⁴].
  • -10⁵ <= Node.val <= 10⁵
  • pos is -1 or a valid index in the linked-list.
linked-listtwo-pointersfloyd
Open on LeetCode ↗
02

Intuition

A list with a loop never reaches null, so walking it to the end never finishes. Send two pointers instead: slow moves one node per round and fast moves two.

  • No loop: fast is always ahead, so it reaches the end first and the walk stops with false.
  • Loop: both pointers end up going round it. Each round, fast closes the gap to slow by exactly one node, so the gap counts down 3, 2, 1, 0 and cannot skip past zero. The pointers land on the same node, which only a loop allows.
How to spot this pattern

"Does this sequence of next steps ever repeat?" with no room for a visited set is the fast and slow pointer pattern. The same trick finds a repeated number in Happy Number and Find the Duplicate Number.

03

Approach

Try it first

Before reading on, write the version that remembers every node it has seen. Then ask what two pointers moving at different speeds would do if the list loops. Aim for O(n) time and O(1) space.

1

Run while fast can take two steps

Start slow and fast at head and loop while fast and fast.next both exist. fast is the pointer that reaches the end first, so these two checks are where a list without a loop stops, and they keep fast.next.next from reading past the end.

2

Move slow by one and fast by two

Each round, set slow = slow.next and fast = fast.next.next. The difference of one node per round is what makes the gap inside a loop shrink steadily instead of staying the same forever.

3

Compare the nodes, not their values

After moving, return true if slow is fast. Different nodes can hold the same value, as in 1 → 2 → 1 with no loop, so only the same node object proves the walk came back.

4

Return false when the loop ends

Leaving the while loop means fast found the end of the list, and a list with an end has no loop. Without a loop this happens after about n / 2 rounds.

04

Code in Python, C++ and Java

▶1from typing import Optional
▶2 
▶3 
▶4class Solution:
▶5 def hasCycle(self, head: Optional[ListNode]) -> bool:
▶6 slow = fast = head
▶7 while fast and fast.next:
▶8 slow = slow.next
▶9 fast = fast.next.next
▶10 if slow is fast:
▶11 return True
▶12 return False
head320-4slow, fastgapslow not in the loop yetboth pointers start on 3
slow3
fast3
Both pointers start at the head. Nothing is compared yet: they are on the same node only because they have not moved. The gap row will count how many nodes fast still needs to catch up with slow once both are in the loop.
head320-4slowfastgap2round 1: slow → 2, fast → 0, different
slow2one step
fast0two steps
Both pointers are now in the loop. fast needs 2 more nodes to reach slow, and each round it gains exactly one, so the gap can only count down to 0.
head320-4slowfastgap21round 2: slow → 0, fast → 2, different
slow0one step
fast2two steps
Both pointers are now in the loop. fast needs 1 more node to reach slow, and each round it gains exactly one, so the gap can only count down to 0.
head320-4slow, fastgap210round 3: both on -4 → loop found, true
slow-4one step
fast-4two steps
Both pointers are on the same node (-4). A list without a loop cannot bring the faster pointer back behind the slower one, so the list loops: return true.
05

Set of visited nodes

Walk the list once and store each node object in a set. A node that is already in the set means the walk has come back, so there is a loop. Reaching None means the list ends. The set holds nodes, not values, because values can repeat.

▶1from typing import Optional
▶2 
▶3 
▶4class Solution:
▶5 def hasCycle(self, head: Optional[ListNode]) -> bool:
▶6 seen = set()
▶7 node = head
▶8 while node:
▶9 if node in seen:
▶10 return True
▶11 seen.add(node)
▶12 node = node.next
▶13 return False
06

Common pitfalls

Comparing before moving

✗ Wrong
while fast and fast.next:
    if slow is fast:
        return True
    slow = slow.next
    fast = fast.next.next
✓ Right
while fast and fast.next:
    slow = slow.next
    fast = fast.next.next
    if slow is fast:
        return True

Both pointers start on head, so the first comparison is always true. On [1, 2] with no loop this returns true before either pointer has moved.

Checking only fast in the loop condition

✗ Wrong
while fast:
    slow = slow.next
    fast = fast.next.next
✓ Right
while fast and fast.next:
    slow = slow.next
    fast = fast.next.next

On [1, 2, 3] with no loop, round one puts fast on node 3. Its next is None, so round two reads None.next and crashes. Any list without a loop and with an odd number of nodes fails this way.

07

Edge cases

Empty list

head is None, so the loop condition fails at once and the answer is false.

One node that points to itself

After one round both pointers are back on that node, so the answer is true.

08

Complexity

Time
O(n)
Space
O(1)
slow first walks the part of the list before the loop. Once both are in the loop, fast is less than one lap behind and gains one node per round, so slow is caught before it finishes a single lap. That is at most n rounds, with two pointers of extra memory.
09

Linked List Cycle FAQ

How is this different from finding where the loop starts?

This problem only asks whether a loop exists, so the first meeting of slow and fast is enough. Linked List Cycle II (LeetCode 142) asks for the node where the loop begins. The meeting node is usually somewhere else in the loop, so 142 adds a second walk from the head to find the start.

Does fast have to move exactly two nodes?

No. When both start at the head, after t rounds they are t and k·t nodes along. Once both are in the loop, any round t that is a multiple of the loop length puts them on the same node, so they always meet. Two is used because it needs the fewest next reads per round and only two null checks.