AceYourInterviews
Checking sign-in…

51. Linked List Cycle Detection

CoreFloyd slow/fast cycle detection

Follow next links conceptually from the supplied head and decide whether this traversal eventually reaches a node already encountered. A cycle can begin at the head or later in the list.

Detect repeated node objects, not repeated values. Leave every input node and link unchanged.

Example 1

Input

N0(5) → N1(5) → null

Output

false

Explanation: Equal values at distinct identities do not form a cycle.

Example 2

Input

N0 → N1 → N2 → N3, with N3.next=N1

Output

true

Explanation: After three rounds slow and fast meet at N3. The meeting object need not be the cycle entry N1.

Example 3

Input

N0.next=N0

Output

true

Explanation: Both pointers move and meet after one round. Initial equality alone is not a test.

Constraints

  • 0 <= nodes per input list <= 105
  • -231 <= node.value <= 231 - 1
  • The next links may form one reachable cycle. Compare node identity, not repeated values.
Hints
Hint 1

A set of previously visited objects solves the task directly. What does a repeated identity prove?

Hint 2

Inside a cycle, what happens to the relative gap when one pointer moves twice as fast?

Hint 3

Move one and two edges under a null-safe guard, then compare references; null exhaustion means no cycle.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Tail into a three-node cycle

[5,5,5,5]
1
true