Problem
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
Intuition
This problem involves finding a cycle in an array where each element in the array represents the next index to jump to. The Floyd's Tortoise and Hare algorithm can be applied to detect a cycle in this context.
Approach
Use two pointers, slow and fast, initialized to the first element of the array.
Move slow one step at a time and fast two steps at a time.
If there is a cycle, the two pointers will eventually meet.
After detecting the cycle, reset one of the pointers (let's say slow) to the beginning.
Move both pointers one step at a time until they meet again. The meeting point is the start of the cycle.
The value at the meeting point is the repeated number.
Complexity
- Time complexity:
The time complexity is O(n), where n is the length of the array. The algorithm makes two passes over the array: the first to detect the cycle and the second to find the start of the cycle.
- Space complexity:
The space complexity is O(1) as the algorithm uses only constant extra space.
Code
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
slow , fast = 0 , 0
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow2 = 0
while True:
slow = nums[slow]
slow2 = nums[slow2]
if slow == slow2:
return slow