Given an array nums containing n distinct numbers in the range [0, n], your task is to return the only number in the range that is missing from the array.
- The array
numscontainsndistinct numbers. - The numbers are guaranteed to be in the range
[0, n]. nrepresents the length of the arraynums.
Example:
Input: nums = [3,0,1]
Output: 2
Explanation: Here, n = 3 (since there are 3 numbers). The full range of numbers should be [0, 1, 2, 3]. The number 2 is missing from the input array.
Solution
We can solve this problem efficiently using a few different approaches.
Summation Method:
- Calculate the
expected sumof all numbers from0tonusing the formulan * (n + 1) / 2. - Calculate the
actual sumof all elements present in thenumsarray. - The missing number is simply the difference between the
expected sumand theactual sum. - This approach has an O(n) time complexity (for summing elements) and **O(1) space complexity`.
- Calculate the
XOR Method (Alternative):
- Initialize a variable
missingwithn. - Iterate from
0ton-1. In each step, XORmissingwith bothi(the expected number) andnums[i](the actual number). - Due to the property
a ^ a = 0anda ^ 0 = a, all numbers present in both the expected range and the array will cancel out, leaving only the missing number. - This also has O(n) time complexity and O(1) space complexity and avoids potential overflow issues with large
n.
- Initialize a variable
Let's provide the Summation Method solution:
class Solution:
def missingNumber(self, nums: list[int]) -> int:
n = len(nums)
# Calculate the sum of numbers from 0 to n
# Formula for sum of an arithmetic series: n * (n + 1) / 2
expected_sum = n * (n + 1) // 2
# Calculate the sum of numbers present in the array
actual_sum = sum(nums)
# The difference is the missing number
return expected_sum - actual_sum
