↻one more pass.
Linked lists · Medium

Find The Duplicate Number: the idea to remember.

Find the repeated value in n plus one integers, each between 1 and n, without changing the array.

Solve on LeetCode ↗

The core insight

Treat each value as a next index, find a cycle meeting point, then locate the cycle entry.

Why it works

The repeated value has multiple incoming edges and is the entry of the cycle reachable from index zero.

The mistake to avoid

After the meeting, reset one pointer before walking both at one step; do not return the meeting point directly.

Time: O(n)Space: O(1)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

// Java reference adapted from neetcode-gh/leetcode (MIT).
// Treat each value as a next index, find a cycle meeting point, then locate the cycle entry.
public int findDuplicate(int[] nums) {
    int slow = 0;
    int fast = 0;

    do {
        slow = nums[slow];
        fast = nums[nums[fast]];
    }

    while (slow != fast);

    int slow2 = 0;

    do {
        slow = nums[slow];
        slow2 = nums[slow2];
    }

    while (slow != slow2);

    return slow2;
}

Java reference adapted from neetcode-gh/leetcode · MIT license

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.