LeetCode 268. Missing Number

Post by ailswan Dec. 14, 2023

268 Missing Number

Problem Statement

link: LeetCode.cn LeetCode

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

Example:

Input: nums = [0,1] Output: 2

Input: nums = [9,6,4,2,3,5,7,0,1] Output: 8

Solution Approach

To find the missing number in the given array, employ the concept of the sum of consecutive integers. Calculate the expected sum of the range [0, n], subtract the actual sum of array elements, and return the result. The formula (n + 1) * n // 2 efficiently computes the expected sum.

Algorithm

  1. Calculate the expected sum of the range [0, n] using the formula (n + 1) * n // 2, where n is the length of the array plus one.
  2. Find the actual sum of the elements in the array using the sum(nums) function. Subtract the actual sum from the expected sum to obtain the missing number in the array.
  3. Return the result as the final output.

Implement

    class Solution:
    def missingNumber(self, nums: List[int]) -> int:
      return (len(nums) + 1) * len(nums)//2 - sum(nums)