Skip to main content

Linked List Cycle

Return True if the linked list has a cycle, otherwise False. Example: [3,2,0,-4] with tail -> index 1 => True

Linked List Cycle is where Floyd's tortoise and hare earns its keep: two pointers, one moving twice as fast, must meet inside any loop. The hash-set answer works but spends O(n) memory you do not need. Get the fast-and-slow rhythm here and cycle-entry and middle-of-list fall out for free.

Examples

You write

has_cycle(head: Optional[ListNode])

  1. Example 1

    Input
    [3,2,0,-4], pos=1
    returns
    true
  2. Example 2

    Input
    [1,2], pos=0
    returns
    true

The pattern behind it

Linked Lists

I reach for it when

  • Nodes point to the next node, and you cannot index into the list.
  • You must reverse, merge, reorder or remove a node.

Say this before you type. Say which pointers you hold and which link you are about to change.

All 12 Linked Lists problems

Two Pointers

I reach for it when

  • The array is sorted, or you can sort it.
  • You need a pair, a triple or a palindrome.

Say this before you type. Say what each pointer means and what a move to the left or right rules out.

All 26 Two Pointers problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Linked List Cycle (Floyd's)easy

Prep guides that list this problem

Our company tags come from public interview write-ups. None of these is a confirmed question.