287. Find the Duplicate Number
## description
## 287. Find the Duplicate Number
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
There is only one repeated number in nums, return this repeated number.
You must solve the problem without modifying the array nums and using only constant extra space.
Example 1:
1Input: nums = [1,3,4,2,2]
2Output: 2Example 2:
1Input: nums = [3,1,3,4,2]
2Output: 3Example 3:
1Input: nums = [3,3,3,3,3]
2Output: 3Constraints:
- –1 <= n <= 105
- –nums.length == n + 1
- –1 <= nums[i] <= n
- –All the integers in nums appear only once except for precisely one integer which appears two or more times.
- –How can we prove that at least one duplicate number must exist in nums?
- –Can you solve the problem in linear runtime complexity?
Follow up:
## notes
### Intuition
Treat the array as a linked list where each value points to the next index. Since there's a duplicate, following these "pointers" creates a cycle. The duplicate is where the cycle begins—finding the cycle's start gives us the answer.
### Implementation
Use Floyd's cycle detection in two phases. First, use fast and slow pointers until they meet—this confirms a cycle and places slow somewhere inside it. Second, start a new pointer at index 0 and advance both it and slow one step at a time. They'll meet at the cycle's start, which is the duplicate value.
### Edge-cases
The first phase only detects that a cycle exists; it doesn't find the start. The second phase is essential for locating the actual duplicate.
- –Time: O(n) — both phases traverse at most n elements
- –Space: O(1) — only using pointers
### Complexity
## solution
1from typing import List
2
3class Solution:
4 def findDuplicate(self, nums: List[int]) -> int:
5 slow, fast = 0, 0
6 while True:
7 slow = nums[slow]
8 fast = nums[nums[fast]]
9 if slow == fast:
10 break
11
12 slow_2 = 0
13 while True:
14 slow_2 = nums[slow_2]
15 slow = nums[slow]
16 if slow == slow_2:
17 return slow
18
19
20
21if __name__ == "__main__":
22 # Include one-off tests here or debugging logic that can be run by running this file
23 # e.g. print(solution.two_sum([1, 2, 3, 4], 3))
24 solution = Solution()
25