#287
Find the Duplicate Number
MediumArrayTwo PointersBinary SearchBit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Using Floyd's Tortoise and Hare algorithm, we can find the duplicate in linear time and constant space. This method uses the properties of linked lists.
⚙️
Algorithm
3 steps- 1Step 1: Initialize two pointers, slow and fast. Both start at the first element.
- 2Step 2: Move slow by one step and fast by two steps until they meet.
- 3Step 3: Reset one pointer to the start and move both pointers one step at a time until they meet again. The meeting point is the duplicate.
solution.py13 lines
1def findDuplicate(nums):
2 slow = nums[0]
3 fast = nums[0]
4 while True:
5 slow = nums[slow]
6 fast = nums[nums[fast]]
7 if slow == fast:
8 break
9 slow = nums[0]
10 while slow != fast:
11 slow = nums[slow]
12 fast = nums[fast]
13 return slowℹ
Complexity note: The time complexity is O(n) because we traverse the array at most twice. The space complexity is O(1) since we only use a few pointers.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.