Menu
CoddyTech

Find the Duplicate Number

You get an array nums of n+1 integers, each between 1 and n. Exactly one value appears more than once, possibly many times, and you return that value.

Solve it without changing nums and with only a constant amount of extra memory.

Function

findDuplicate(nums: integer-array) → integer
numsinteger-array
n+1 integers, each between 1 and n
Returnsinteger
the value that appears more than once

Constraints

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

Examples

Input
nums = [2, 5, 1, 3, 5, 4]
Output
5
Explanation
Here n is 5, and 5 sits at positions 1 and 4, so the answer is 5. Every other value from 1 to 5 appears once.

lock icon+17 hidden tests on Submit

challenge icon

Follow-up

The binary search on values keeps both rules in O(n log n) time. Can you keep them in O(n) time?

Reset code
def findDuplicate(nums):
    # Write code here
Test cases

Case 1

Case 2

Input

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

Expected

5