PracticeNeetCode ↗LeetCode ↗
Given the head of a linked list, determine whether the list contains a cycle — some node's next eventually points back to a node earlier in the list.
fast (or fast.next) ever becomes None, the list terminates cleanly — there's no cycle.slow = head, fast = head.fast and fast.next are not None: move slow one step, fast two steps.slow is fast, a cycle exists — return True.fast (or fast.next) is None, return False.Time: O(n) — Space: O(1)
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def hasCycle(head: ListNode | None) -> bool:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return FalseHow the solution above works, piece by piece.
slow moves one step, fast two steps.while fast and fast.next: if fast reaches the end, there is no cycle.slow is fast compares node identity, not values; different nodes can hold the same value.Running it on [3, 2, 0, -4] with the tail linked to index 1:
None.