find-the-duplicate-number.sh — zsh

Find the Duplicate Number

medium
arraystwo-pointerscycle-detection

You are given an array nums containing n + 1 integers where each value is in the range [1, n] inclusive. Exactly one integer value is duplicated; it may appear more than twice, but no second distinct value is duplicated. Return that repeated value.

You must solve the problem without modifying the array and using only O(1) extra space.

Input / output

  • Input: nums: int[]
  • Output: int

Examples

  1. nums = [1,3,4,2,2] returns 2.
  2. nums = [3,1,3,4,2] returns 3.
  3. nums = [1,1] returns 1.

Constraints

  • 1 <= n <= 10^5
  • nums.length == n + 1
  • 1 <= nums[i] <= n
  • Exactly one integer value appears at least twice; all other values appear at most once.
  • You must not modify nums.
  • You must use only constant extra space.

Follow-up How would you solve it if you were allowed O(n) extra space (for example, a hash set), or if modifying the array were allowed? Can you also explain why viewing the array as a functional graph i -> nums[i] guarantees a cycle whose entrance is exactly the duplicate value?

Examples
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 = [1,1]
Output: 1