00:00

Problem Statement

Input/Output Examples

Visual Explanation

Once both pointers are inside the loop, the gap between them shrinks by one each step, so they must meet within one lap. Without a loop, the fast pointer simply reaches null.

Approaches

Floyd's method uses two pointers and no extra memory. The set method remembers every node visited.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the number of nodes. Both approaches finish within a constant number of passes; only the set needs memory for every node.

Interview Tips and Recommended Approach

  • Check both fast and fast.next before moving two steps.
  • Compare references, not values. Two nodes can hold the same value.
  • Know the follow-up. Restarting one pointer at the head and moving both one step finds where the cycle begins.
  • Do not mark nodes by changing their values or links; that modifies the input.

Recommended Approach: Floyd's Tortoise and Hare

Why: it detects any cycle with two pointers and no extra memory, and it extends naturally to finding where the cycle starts.