Date and Time: Jul 31, 2024, 22:59 (EST)
Link: https://leetcode.com/problems/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 uses only constant extra space.
Example 1:
Input: nums = [1,3,4,2,2]
Output: 2
Example 2:
Input: nums = [3,1,3,4,2]
Output: 3
Example 3:
Input: nums = [3,3,3,3,3]
Output: 3
-
1 <= n <= 10^5
-
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.
This question can be converted into Linked-list question. We can think of the elements in nums
to represent the index of nums
, because we are guaranteed that [1, n]
and at most n + 1
integers.
Then, we can use Floyd's Tortoise and Hare Algorithm to find the cycle by having fast = nums[nums[fast]]
and slow = nums[slow]
pointers. Next, we intialize slow2 = 0
and we run the while loop again until slow = slow2
, and return slow
the repeated number.
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
fast, slow = 0, 0
while True:
fast, slow = nums[nums[fast]], nums[slow]
if fast == slow:
break
slow2 = 0
while True:
slow, slow2 = nums[slow], nums[slow2]
if slow == slow2:
return slow
Time Complexity:
Space Complexity: