268. Missing Number

268. Missing Number

Code:

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        

Approach:

  1. 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.
  2. 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.
  3. Finally, the variable res is returned, which represents the missing number in the array.

Time Complexity: O(n)

Space Complexity: O(1)

No alt text provided for this image


To view or add a comment, sign in

More articles by Irfan Ahmed Mohammad

Insights from the community

Others also viewed

Explore topics