LeetCode 287. Find the Duplicate Number

Description

https://leetcode.com/problems/find-the-duplicate-number/

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 uses 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 = [1,1]
Output: 1

Example 4:

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

Constraints:

  • 2 <= 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?

Explanation

Store the number occurrence in a fixed-length array and check which number occurs more than once.

Python Solution

class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        
        count = [0 for i in range(len(nums) + 1)]
        
        
        for num in nums:
            count[num] += 1
            
            if count[num] > 1:
                return num
        
  • Time Complexity: O(N).
  • Space Complexity: O(1).

One Thought to “LeetCode 287. Find the Duplicate Number”

  1. The space complexity is not correct because it creates an extra array of size N + 1, so the extra space complexity is O(N) not O(1)

Leave a Reply

Your email address will not be published. Required fields are marked *