|
| 1 | +# https://neetcode.io/problems/find-duplicate-integer |
| 2 | + |
| 3 | +import unittest |
| 4 | + |
| 5 | + |
| 6 | +def find_duplicate(nums: list[int]) -> int: |
| 7 | + # Use Floyd's Tortoise and Hare algorithm to detect cycles. |
| 8 | + # This algorithm is used here to find the duplicate number in the list. |
| 9 | + # The problem guarantees that there is exactly one duplicate number. |
| 10 | + |
| 11 | + # Initialize both pointers to the start of the list. |
| 12 | + slow = nums[0] |
| 13 | + fast = nums[0] |
| 14 | + |
| 15 | + # Phase 1: Finding the intersection point of the two pointers. |
| 16 | + # Move 'slow' by one step and 'fast' by two steps until they meet. |
| 17 | + # Since there is a duplicate, a cycle must exist, and they will meet inside the cycle. |
| 18 | + while True: |
| 19 | + slow = nums[slow] # Move slow pointer by one step. |
| 20 | + fast = nums[nums[fast]] # Move fast pointer by two steps. |
| 21 | + |
| 22 | + if slow == fast: |
| 23 | + # Pointers have met, indicating a cycle. |
| 24 | + break |
| 25 | + |
| 26 | + # Phase 2: Finding the entrance to the cycle, |
| 27 | + # which is the duplicate number. |
| 28 | + slow = nums[0] # Move slow pointer back to the start of the list. |
| 29 | + |
| 30 | + # Move both pointers at the same speed until they meet again. |
| 31 | + # The meeting point is the start of the cycle, i.e., the duplicate number. |
| 32 | + while slow != fast: |
| 33 | + slow = nums[slow] # Move slow pointer by one step. |
| 34 | + fast = nums[fast] # Move fast pointer by one step. |
| 35 | + |
| 36 | + return slow # The duplicate number. |
| 37 | + |
| 38 | + |
| 39 | +class Test(unittest.TestCase): |
| 40 | + def test(self): |
| 41 | + self.assertEqual(find_duplicate([1, 3, 4, 2, 2]), 2) |
| 42 | + self.assertEqual(find_duplicate([3, 1, 3, 4, 2]), 3) |
| 43 | + self.assertEqual(find_duplicate([1, 1]), 1) |
| 44 | + self.assertEqual(find_duplicate([1, 1, 2]), 1) |
0 commit comments