832. Find the repeated id without modifying the list or using extra memory
A list holds n + 1 integer ids, each between 1 and n inclusive. By counting, at least one id must repeat. Exactly one id value is repeated, though it may appear more than twice.
Write find_duplicate(nums) that returns the repeated id. Do not modify the list, and use only a constant amount of extra memory (so no set and no sorting a copy).
def find_duplicate(nums)Example 1
Input: find_duplicate([1, 3, 4, 2, 2])
Output: 2
Example 2
Input: find_duplicate([3, 1, 3, 4, 2])
Output: 3
Constraints
- 2 <=
len(nums)<= 100,000 - 1 <=
nums[i]<=len(nums)- 1
Hint 1
Index 0 is never a value, so it is a safe start.
Hint 2
First find a meeting point inside the cycle.
Hint 3
Then walk two pointers at the same speed.
Common mistakes
- Sorting or marking values in place, which modifies the list.
- Using a set, which breaks the memory limit.
- Starting phase two from the meeting point for both pointers.
Understand the idea
The constraint "values are in 1..n" turns the array into a linked structure where nums[i] is the next pointer. A repeated value means two nodes share a successor, which creates a cycle with an entrance at that value. Floyd's algorithm finds a cycle entrance in O(n) time and O(1) memory. The math: if the tail has length a and they meet b steps into a cycle of length c, then a is a multiple of c minus b, so a pointer from the start and one from the meeting point arrive at the entrance together.