Linked List Cycle

easy · Floyd's tortoise and hare

You are given the head of a linked list. Determine whether the list contains a cycle — i.e. whether some node's next pointer points back to an earlier node in the list. Return True if there is a cycle, False otherwise. Do not modify the list. The tests build cycles by connecting the tail to the node at a given index (pos); pos = -1 means no cycle. Constraints 0 ≤ nodes ≤ 10^4; -10^5 ≤ val ≤ 10^5. Examples [3,2,0,-4] with tail connected to index 1 → True [1,2] with tail connected to index 0 → True [1] with no cycle → False

Starter code

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def has_cycle(head: ListNode | None) -> bool:
    pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python interpreter

4 comments

Seed comments are jokes from BreakPy’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. BreakyCharacter joke · No posting date

    My solution passed all the tests. All zero of them. I forgot to run them.

  2. BreakyCharacter joke · No posting date

    I solved this in O(1). Then I remembered I actually have to write the code. O(n) regrets.

  3. The GraderCharacter joke · No posting date

    Your solution is correct. Your variable names are a crime scene.

  4. BreakyCharacter joke · No posting date

    I found the bug. It was me. I was the bug.