oneby7

Linked Lists Fast and slow pointers

294. Find the Duplicate Number

Medium

You are given an array nums of n + 1 integers, each between 1 and n. Exactly one value appears more than once. It may appear twice or many times; when it appears more than twice, some values from 1 to n do not appear at all. Return the value that repeats.

Do not change nums, and use only O(1) extra memory. If nums is different after your function returns, the output shows the array was changed instead of your answer.

Example 1

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

Output: 5

Explanation: 5 appears at indices 3 and 4. Every other value from 1 to 5 appears once.

Example 2

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

Output: 4

Explanation: 4 appears four times, and 2 and 3 do not appear at all.

Example 3

Input: nums = [1, 1]

Output: 1

Explanation: Here n = 1, so the only allowed value is 1, and both numbers are 1.

Check your understanding

Work out the answer for this input before you write any code.

nums = [2, 6, 4, 1, 3, 6, 5]

Constraints

  • 1 ≤ n ≤ 105
  • nums.length == n + 1
  • 1 ≤ nums[i] ≤ n
  • Exactly one value appears two or more times. Every other value appears at most once.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.