DevPath

← All problems

Missing Number

Easy arrays · math

Description

Given an array containing n distinct numbers from 0 to n, return the one number in that range that is missing.

Constraints

1 <= n <= 100000

Examples

Input: nums = [3,0,1]

Output: 2

Hints (1)
  • The sum of 0..n is n*(n+1)/2; subtract the array sum.

Solutions

Arithmetic-series sum minus array sum. · Time O(n) · Space O(1)

func missingNumber(nums []int) int {
    n := len(nums)
    expected := n * (n + 1) / 2
    sum := 0
    for _, v := range nums {
        sum += v
    }
    return expected - sum
}

Create a free account to submit solutions, track progress and save problems.

Create account