SDE & MLE Prep

287. Find the Duplicate Number

Problem

nums has n + 1 integers, each in [1, n], so at least one value repeats; exactly one value is repeated (possibly many times). Return it without modifying nums, using O(1) extra space.

Example: [1,3,4,2,2] → 2; [3,1,3,4,2] → 3

Constraints: follow-up: better than O(n²).

Values in [1, n] → view i → nums[i] as a linked list. The duplicate value is where two arrows enter the same node = cycle entrance (Floyd, like 142). No modification, O(1) space.

Complexity: O(n) time, O(1) space.

class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        slow = fast = 0
        while True:
            slow, fast = nums[slow], nums[nums[fast]]
            if slow == fast:
                break
        p = 0
        while p != slow:
            p, slow = nums[p], nums[slow]
        return p