codejump
MediumPro challengePythonJavaScriptTypeScript

Linked List — Find the Duplicate Number

AlgorithmsLinked ListTwo PointersCycle Detection

solve(nums) — nums has n + 1 integers, each between 1 and n (inclusive), so at
least one value repeats. Exactly one value is the repeated one (it may appear more than
twice). Return it without modifying `nums` and using only O(1) extra space — no
sorting, no Set, no counting array.

Treat the array as a linked list: index i points to index nums[i]. Because two
indexes hold the same value, two "nodes" point to the same next node, so the walk from
index 0 enters a cycle, and the duplicate is the node where the cycle begins. Find it
with Floyd's two-phase algorithm: meet inside the cycle, then restart one pointer from the
start and move both one step at a time.

Examples

solve([1,3,4,2,2])  → 2
solve([3,1,3,4,2])  → 3
solve([3,3,3,3,3])  → 3

Sample tests

Test #1Classic example
Input: [[1,3,4,2,2]]
Output: 2
Test #2Duplicate at both ends
Input: [[3,1,3,4,2]]
Output: 3
Test #3Repeated many times
Input: [[3,3,3,3,3]]
Output: 3