NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior0 views

LeetCode #141 — You are given an interface for a linked list, LLI, with a single method, next, which returns the next element. Write a function that returns True if the list contains a cycle and False if it does not.

Practice

AI answer

I’ll use Floyd’s algorithm: one pointer moves one step at a time, while the other moves two steps. If the pointers meet, there is a cycle; if the fast pointer reaches the end (None), there is no cycle. Time complexity is O(n), and extra space complexity is O(1).

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

You need to compare the nodes themselves, not their values: different nodes can contain identical data.