Data structures problem 15 of 30

Does the list loop?

  • Data structures
  • Medium

Given the head of a singly linked list, return True if the list contains a cycle (some node's next points back to an earlier node). Use O(1) extra space.

Show hint

Send two pointers down the list at different speeds. If there is a loop, what must eventually happen?

Show solution
def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            return True
    return False

This is Floyd's "tortoise and hare". Without a loop, the fast pointer reaches the end. With a loop, the fast pointer gains one step per round on the slow one inside the cycle, so they must meet. O(n) time, O(1) space.

Want a problem like this every day? See today's problem and keep a streak going.