Leetcode problem: 287. Find the Duplicate Number

Description:

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.

Example 1:

Input: nums = [1,3,4,2,2]
Output: 2

Example 2:

Input: nums = [3,1,3,4,2]
Output: 3

Example 3:

Input: nums = [3,3,3,3,3]
Output: 3

Constraints:

  • 1 <= n <= 105
  • 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.

Follow up:

  • How can we prove that at least one duplicate number must exist in nums?
  • Can you solve the problem in linear runtime complexity?

Solution:

class Solution {
    public int findDuplicate(int[] nums) {
        int len = nums.length;
        int[] unique = new int[len];

        for(int num:nums){
            if(unique[num] == 0){
                unique[num] = 1;
            }
            else{
                return num;
            }
        }

        return -1;
    }
}

Problem Statement

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), exactly one number is repeated. Return the duplicate number.

Approach Explanation

  1. Create a helper array (unique) to track seen numbers
    • Since numbers are between 1 and n, we can use an array of size len (length of nums) as a checklist.
    • Initially, all entries in unique are 0.
  2. Iterate through the nums array
    • For each number num in nums:
      • Check unique[num]:
        • If it is 0 → this number hasn’t been seen yet → mark it as seen (unique[num] = 1)
        • If it is 1 → this number has already been seen → return it as the duplicate
  3. Return -1 if no duplicate is found
    • This is just a fallback, but the problem guarantees a duplicate exists, so normally this won’t be reached.
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , CodesToolbox
Scroll to Top
0
Would love your thoughts, please comment.x
()
x