Find the Duplicate Number

You are given an array nums of n + 1 integers, where every value is between 1 and n inclusive. There are more slots than possible values, so some value must repeat. Here exactly one value repeats, although it may appear more than twice.

Return that repeated value.

You must not modify nums (so no sorting it and no marking values in place), and you should use only O(1) extra space.

Constraints

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

Examples

Example 1

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

4 appears twice; every other value appears once.

Example 2

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

The duplicate may repeat more than twice. Here 1 and 3 are missing and 2 fills their places.

Example 3

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

The smallest possible input: n = 1.

JavaScript you'll use: Arrays: create, read, update Map and Set

/**
 * @param {number[]} nums
 * @return {number}
 */
function findDuplicate(nums) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.