Find the Duplicate Number

Medium#287cycle

You get an array of n + 1 numbers, each from 1 to n, so at least one number repeats; exactly one value repeats, maybe more than twice. Find it without changing the array and with O(1) extra memory. Our example: [3, 5, 4, 6, 1, 2, 1], n = 6 — the answer is 1.

input
nums: n + 1 integers, each from 1 to n. Exactly one value repeats, maybe more than twice.
returns
The value that repeats. LeetCode wants it without changing nums and with O(1) extra memory.
constraints
  • 1 ≤ n ≤ 10⁴, nums.length = n + 1
  • 1 ≤ nums[i] ≤ n
  • exactly one value repeats
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @return {number}
 */
function findDuplicate(nums) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more fast and slow pointers problems

Pattern “Fast and slow pointers” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.