Skip to main content

Find the Duplicate Number

MediumPremium

You're given an array nums of n + 1 integers, where every value is between 1 and n inclusive. Exactly one value appears more than once, possibly many times. Return that value.

Solve it without changing nums and using only O(1) extra space.

Example 1

Input: nums = [1, 3, 4, 2, 2] Output: 2

The array holds five values from 1 to 4, and 2 is the one that repeats.

Example 2

Input: nums = [3, 3, 3, 3, 3] Output: 3

The repeated value can fill most of the array.

Constraints

  • 1 <= n <= 10^5
  • nums.length == n + 1
  • 1 <= nums[i] <= n
  • Exactly one value appears two or more times.