PracticeNeetCode ↗LeetCode ↗
Given an array nums of n + 1 integers where every value lies in the range [1, n], exactly one value repeats (possibly more than twice). Find that duplicate without modifying the array and using only O(1) extra space.
i "points to" index nums[i] — a duplicate value creates a cycle in that list.slow = nums[0], fast = nums[0].slow = nums[slow] and fast = nums[nums[fast]] until slow == fast.slow = nums[0]; advance both slow and fast one step at a time until they meet again.Time: O(n) — Space: O(1)
def findDuplicate(nums: list[int]) -> int:
slow, fast = nums[0], nums[0]
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow = nums[0]
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slowHow the solution above works, piece by piece.
i → nums[i] from index 0 never leaves the array and must eventually loop.slow takes one hop, fast two, until they meet somewhere in the loop.slow at the beginning and move both one hop at a time. The distance maths of Floyd's algorithm makes them meet exactly at the loop entry.Running it on nums = [1, 3, 4, 2, 2]:
nums[i]. Two indices (3 and 4) both point to 2, so 2 is where the path enters a loop, and that entry node is the duplicate. Floyd's algorithm finds a meeting point in the loop, then the loop's entry.