Skip to content
Problem 287 · LeetCode 287(opens in a new tab)

Find the Duplicate Number

MediumArrays

You get an array nums of n + 1 whole numbers, each between 1 and n. Since there are more slots than possible values, at least one value has to repeat. In fact exactly one value repeats, and it may appear two times or more.

Return that repeated value. Do not change nums, and use only a constant amount of extra memory.

Example 1

Input:  nums = [3, 4, 4, 2, 5, 1]
Output: 4
Why:    4 sits at positions 1 and 2
2 more examples and the constraints

Example 2

Input:  nums = [1, 1]
Output: 1
Why:    n = 1, so both slots hold 1

Example 3

Input:  nums = [2, 2, 2, 2, 2]
Output: 2
Why:    the repeat can fill many slots

Constraints

  • 1 ≤ n ≤ 100,000, and nums has n + 1 elements
  • Every element is between 1 and n
  • Exactly one value appears more than once; each other value appears at most once

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Brute forceO(n²)
  2. Binary search on the valueO(n log n)
  3. Floyd’s cycle detectionO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,001 numbersVerdict
Brute forceO(n²)
Mention it, then move on
Binary search on the valueO(n log n)
Passes; easy to argue
Floyd’s cycle detectionO(n)
Best; linear and O(1) memory

n = the largest allowed value; the array has n + 1 numbers.

Edge cases to test

  • Smallest input. [1, 1]: n = 1, the answer is 1.
  • Repeat appears many times. [2, 2, 2, 2, 2]: some values from 1 to n are missing, which is allowed.
  • Repeat at the two ends. [5, 1, 2, 3, 4, 5]: the first and last positions.
  • Largest value repeated. [1, 2, 3, 4, 5, 6, 6]: the repeat is n itself.

Common mistakes

  • Starting the pointers at nums[0] in one phase and at 0 in the other, so the two phases disagree.
  • Returning the meeting point of phase 1. It is inside the loop, not always at its entrance.
  • Sorting nums or marking values negative. Both change the array, which is not allowed.

How to talk through it

  1. 1Clarify. Can the repeat appear more than twice? Can I change the array? How much memory do I have?
  2. 2Give the brute force. Compare every pair: O(n²). Mention that a set or a sort is faster but breaks a rule.
  3. 3Binary search the value. Counting numbers ≤ mid gives O(n log n) with O(1) memory.
  4. 4Reframe as a linked list. Index i points to nums[i]; the repeat is the loop entrance. Code the two phases of Floyd.
  5. 5Test out loud. Run [1, 1] and a case where the repeat appears three times.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?