You are given an array nums containing n distinct numbers in the range [0, n]. Your task is to find and return the only number in the range that is missing from the array.
nis the length ofnums.1 <= n <= 10^40 <= nums[i] <= n- All numbers in
numsare unique.
Example 1:
Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 (length of array). The range is [0,3]. Numbers in array are 0, 1, 3. The missing number is 2.
Solution
Several approaches can solve this problem efficiently.
- Approach 1: Summation
- Calculate the expected sum of all numbers from
0tonusing the formulan * (n + 1) / 2. - Calculate the actual sum of all numbers present in the
numsarray. - The missing number is simply the
expected_sum - actual_sum. - This approach has O(n) time complexity and O(1) space complexity.
- Calculate the expected sum of all numbers from
- Approach 2: XOR (Bit Manipulation)
- Initialize a variable
missingwithn. - Iterate from
i = 0ton-1. For eachiand the corresponding numbernumatnums[i]:missing = missing ^ i ^ num
- The final value of
missingwill be the missing number. This works because XORing a number with itself results in0, and XORing with0returns the number itself. All present numbers (bothiandnums[i]) will cancel out, leaving only the missing one. - This approach also has O(n) time complexity and O(1) space complexity, and is robust against potential integer overflow for very large
nwhere the sum might exceed standard integer limits (though not a concern for the given constraints ofn <= 10^4).
- Initialize a variable
Let's use the Summation approach for the code example:
class Solution:
def missingNumber(self, nums: list[int]) -> int:
n = len(nums)
# Calculate the expected sum of numbers from 0 to n
expected_sum = n * (n + 1) // 2
# Calculate the actual sum of numbers in the array
actual_sum = sum(nums)
# The missing number is the difference
return expected_sum - actual_sum
