Skip to content

LC 268. Missing Number

mccornet edited this page Jul 24, 2021 · 7 revisions

268. Missing Number

Challenge

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.

Solution:

Using math wikipedia to calculate the sum of the first consecutive integers:

  • sum = 1/2 * n * (n+1)

Python Code

class Solution:

    def missingNumber(self, nums: list[int]) -> int:
        length = len(nums)
        math_sum = (length * (length+1)) // 2
        missing = math_sum - sum(nums)
        return missing

Clone this wiki locally