class Solution:
def missingNumber(self, nums: List[int]) -> int:
n = len(nums)
res = n
for i in range(n):
res += (i-nums[i])
return res
- The approach used here is based on the mathematical formula for the sum of the first n natural numbers: sum = n*(n+1)//2. First, the length of the array nums is assigned to the variable n. Then, the variable res is initialized to n, which represents the sum of the first n natural numbers plus the missing number.
- Next, a for loop is used to iterate over the indices and values of the array nums. In each iteration, the difference between the index i and the value nums[i] is added to the variable res. This has the effect of subtracting the missing number from res, since the missing number will not have a corresponding index-value pair in nums.
- Finally, the variable res is returned, which represents the missing number in the array.