Find the Duplicate Number

Medium Two Pointers AI round

nums is a list of n + 1 whole numbers, each from 1 to n.

Exactly one number appears more than once. It may appear many times, and then some numbers from 1 to n are missing. Every other number appears once at most.

Return the number that appears more than once.

Try to leave nums as it is and to use only a fixed amount of extra memory, however long the list is.

Example 1

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

5 is at places 3 and 6, counting from 0. Every number from 1 to 6 is in the list, and 5 is the only one there twice.

Example 2

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

2 appears three times, so 3 is missing: the five places hold only 1, 2 and 4, with 2 in three of them.

Example 3

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

Constraints

  • 1 ≤ n ≤ 4 × 10⁵
  • nums.length = n + 1
  • 1 ≤ nums[i] ≤ n
  • Exactly one number appears more than once

Watch the explanation

More Two Pointers

All Two Pointers problems