Missing Number

Easy

Topics
ArrayMathBit Manipulation

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

Example 1

300112
The 3 values should be a permutation of 0..3, which sums to 6. They sum to 4, so the missing value is the difference, 2.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [3,0,1]
Output: 2

Example 2

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

Constraints

  • n == nums.length
  • 1 <= n <= 10^4
  • All numbers are distinct and in [0, n].
Editorial — intuition, approach, complexity and pitfalls

Intuition

The full set 0..n has a known sum, n(n+1)/2. Subtract the sum of the array you were given, and the leftover is precisely the missing number.

Approach

  1. Compute the expected sum n(n+1)/2 for n = len(nums).
  2. Subtract the actual array sum.
  3. Return the difference.

Walkthrough

nums = [3, 0, 1], n = 3
expected = 3*4/2 = 6
actual   = 3+0+1 = 4
missing  = 6 - 4 = 2

Complexity

  • Time — O(n): one pass to sum.
  • Space — O(1): arithmetic only.

Common Pitfalls

  • With huge n, the sum can overflow fixed-width ints — XOR of indices and values avoids that.

Full Solution — all languages

class Solution:
    def missingNumber(self, nums):
        n = len(nums)
        return n * (n + 1) // 2 - sum(nums)
Asked at BlackRock
SensAI
Beta
Tap the mic to stop voice mode