Find the Duplicate Number - Problem

You're given an array nums containing n + 1 integers, where each integer is in the range [1, n] inclusive. Here's the catch: exactly one number appears twice, while all others appear exactly once.

Your mission: Find that duplicate number!

The Challenge: You must solve this without modifying the original array and using only constant extra space (O(1)).

Example: If nums = [1,3,4,2,2], then n = 4 and we have 5 integers. The duplicate is 2.

This problem has several elegant solutions - from brute force to a brilliant cycle detection approach that treats the array like a linked list!

Input & Output

example_1.py — Basic Case
$ Input: [1,3,4,2,2]
Output: 2
💡 Note: The number 2 appears twice in the array, so it's the duplicate we need to find.
example_2.py — Different Duplicate
$ Input: [3,1,3,4,2]
Output: 3
💡 Note: Here, the number 3 appears at indices 0 and 2, making it the duplicate number.
example_3.py — Minimum Size
$ Input: [1,1]
Output: 1
💡 Note: With n=1, we have 2 elements. Since both are 1, the duplicate is 1.

Visualization

Tap to expand
The Evolution of SolutionsBrute ForceO(n²) timeO(1) spaceCompare all pairsBinary SearchO(n log n) timeO(1) spaceSearch answer rangeFloyd's AlgorithmO(n) timeO(1) spaceCycle detectionArray as Linked List Visualization:Array: [1, 3, 4, 2, 2] → Each value points to next indexStart1342Cycle!Duplicate = 2🎯 Key Insight: The duplicate number is where the cycle begins!Floyd's algorithm finds this entry point in O(n) time with O(1) space
Understanding the Visualization
1
The Problem Setup
We have n+1 numbers in range [1,n], so one number must appear twice by pigeonhole principle
2
Brute Force Approach
Compare every pair - like checking every combination of keys to find matching room numbers
3
Binary Search Insight
Count elements ≤ mid value. If count > mid, duplicate is in lower half of range
4
The Cycle Detection Breakthrough
Treat array as linked list. Duplicate creates cycle. Find cycle start using Floyd's algorithm
Key Takeaway
🎯 Key Insight: The duplicate number creates a cycle when we treat the array as a linked list. Floyd's cycle detection algorithm elegantly finds where this cycle begins in optimal time and space complexity!

Time & Space Complexity

Time Complexity
⏱️
O(n)

Each pointer traverses the array at most twice, giving us linear time

n
2n
Linear Growth
Space Complexity
O(1)

Only using two pointer variables, constant extra space

n
2n
Linear Space

Constraints

  • 1 ≤ n ≤ 105
  • nums.length == n + 1
  • 1 ≤ nums[i] ≤ n
  • All integers in nums appear only once except for exactly one integer which appears twice
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 28 Apple 22
68.3K Views
High Frequency
~25 min Avg. Time
2.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