Tutorialspoint
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.
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.
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)
ArraysWalmartSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Initialize two pointers (slow and fast) both pointing to the first element of the array.

 Step 2: Move slow pointer one step at a time and fast pointer two steps at a time until they meet.
 Step 3: This meeting point indicates there's a cycle in the "linked list" representation of the array.
 Step 4: Reset the slow pointer to the beginning of the array.
 Step 5: Move both pointers one step at a time until they meet again.
 Step 6: The meeting point is the entrance to the cycle, which is our duplicate number.
 Step 7: Return the duplicate number found.

Submitted Code :