Find the Duplicate Number

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive, there is exactly one repeated number. Find and return this duplicate number.

You must solve this problem without modifying the array nums and using only constant extra space.

Examples

Example 1:

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

Output: 2

Explanation: The number 2 appears twice, so it is the duplicate.

Example 2:

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

Output: 3

Explanation: The number 3 appears twice, so it is the duplicate.

Example 3:

Input: nums = [1, 1]

Output: 1

Explanation: The only possible number is 1, and it appears twice.

Constraints

  • 1 <= n <= 10^5
  • nums.length == n + 1
  • 1 <= nums[i] <= n
  • There is only one repeated number in nums, but it could be repeated more than once.
Source: Fast and Slow Pointers pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle