
Problem
Solution
Submissions
Find Duplicate Number in Array
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to find the duplicate number in an array containing n+1 integers where each integer is between 1 and n (inclusive). There is only one repeated number but it could be repeated more than once. You must solve this without modifying the array and using only constant extra space.
Example 1
- Input: nums = [1,3,4,2,2]
- Output: 2
- Explanation:
- The array contains numbers from 1 to 4, but has 5 elements.
- Number 2 appears twice in the array at indices 3 and 4.
- Therefore, 2 is the duplicate number.
- The array contains numbers from 1 to 4, but has 5 elements.
Example 2
- Input: nums = [3,1,3,4,2]
- Output: 3
- Explanation:
- The array contains numbers from 1 to 4, but has 5 elements.
- Number 3 appears twice in the array at indices 0 and 2.
- Therefore, 3 is the duplicate number.
- The array contains numbers from 1 to 4, but has 5 elements.
Constraints
- 1 ≤ n ≤ 10^5
- nums.length == n + 1
- 1 ≤ nums[i] ≤ n
- All the integers in nums appear only once except for precisely one integer which appears two or more times
- You must not modify the array
- You must use only constant extra space
- Time Complexity: O(n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Treat the array indices and values as a linked list where nums[i] points to nums[nums[i]]
- Use two pointers (slow and fast) to detect the cycle
- Once a cycle is detected, find the entrance point of the cycle
- The entrance point will be the duplicate number