You have been given an array containing n
distinct numbers taken from the range [0, n]
. Since the array contains n
numbers, exactly one number is missing from the range. Your task is to find and return that missing number.
Example:
Input: [3,0,1]
Output: 2
Input: [0,1]
Output: 2
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
[0, n]
where n
is at least 1.Given the problem, we can use the following approach:
n
natural numbers can be computed using the formula:
[
\text{Sum} = \frac{n \times (n + 1)}{2}
]
[0, n]
.Here’s the implementation using the sum formula approach:
def missingNumber(nums):
n = len(nums)
total_sum = n * (n + 1) // 2
array_sum = sum(nums)
return total_sum - array_sum
n
is the number of elements in the array. We compute the sum of the array which takes linear time.This code effectively calculates the missing number by leveraging the mathematical properties of the sum of the first n
natural numbers.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?