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 Number INPUT Array: nums = [1, 3, 4, 3, 2] 1 i=0 3 i=1 4 i=2 3 i=3 2 i=4 Treat as Linked List: index --> nums[index] 0 1 3 4 CYCLE! Constraints: - n+1 integers in range [1,n] - O(1) space, no modification - Exactly one duplicate exists ALGORITHM STEPS Floyd's Cycle Detection 1 Initialize Pointers slow = fast = nums[0] 2 Phase 1: Find Meeting slow = nums[slow] fast = nums[nums[fast]] Until slow == fast 3 Reset Slow Pointer slow = nums[0] 4 Phase 2: Find Entry Move both one step slow = nums[slow] fast = nums[fast] Until slow == fast Phase 1 Trace: slow: 1-->3-->3 (meet) fast: 1-->4-->3-->3 (meet) Phase 2: Entry = 3 FINAL RESULT Duplicate Found at Cycle Entry Duplicate: 3 Output: return 3 Verification: OK nums[1] = nums[3] = 3 Complexity Analysis Time: O(n) - Two passes through array Space: O(1) - Only two pointers used Key Insight: The array can be viewed as a linked list where each index points to nums[index]. Since values are in [1,n] and there's a duplicate, there must be a cycle. The duplicate number is the entry point of this cycle, which can be found using Floyd's Tortoise and Hare algorithm - just like detecting a cycle in a linked list! TutorialsPoint - Find the Duplicate Number | Floyd's Cycle Detection (Optimal Solution)
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