Skip to content
Decoder

Find the Duplicate Number

Medium

Problem

You get an array nums of n + 1 integers, where every value is between 1 and n. By the pigeonhole principle at least one value repeats, and in fact exactly one value does (it may appear more than twice). Return that value without modifying the array and using only constant extra space.

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 = [3, 3, 3, 3, 3]
Output
3

Hint for the shape: treat each index i as a node whose next is nums[i].

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.