Find the Duplicate Number - Problem

Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

There is only one repeated number in nums, return this repeated number.

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

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,4,3,2]
Output: 3
💡 Note: The number 3 appears at indices 1 and 3, making it the duplicate number
Example 2 — Duplicate at End
$ Input: nums = [3,1,3,4,2]
Output: 3
💡 Note: The number 3 appears at indices 0 and 2, so 3 is the duplicate
Example 3 — Minimum Size
$ Input: nums = [1,1]
Output: 1
💡 Note: With only 2 elements in range [1,1], the duplicate must be 1

Constraints

  • 1 ≤ n ≤ 105
  • nums.length == n + 1
  • 1 ≤ nums[i] ≤ n
  • All integers in nums appear only once except for precisely one integer which appears two or more times.

Visualization

Tap to expand
Find the Duplicate NumberArray has n+1 integers in range [1,n] with exactly one duplicate13432Index 0Index 1Index 2Index 3Index 4Value 3 appears at indices 1 and 3Output: 3Challenge: Find duplicate without modifying array, O(1) spaceBest solution: Floyd's Cycle Detection O(n) time, O(1) space
Understanding the Visualization
1
Input
Array with n+1 integers, one appears twice
2
Process
Find the number that appears more than once
3
Output
Return the duplicate number
Key Takeaway
🎯 Key Insight: Transform into cycle detection by treating array values as pointers to indices
Asked in
Microsoft 45 Apple 38 Amazon 35 Google 32
78.0K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen