Skip to content

Missing Number

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

InputOutputExplanation
[3, 0, 1]2Range 0–3, 2 is missing
[0, 1]2Range 0–2, 2 is missing
[9,6,4,2,3,5,7,0,1]8Range 0–9, 8 is missing
  • n == nums.length
  • 1 <= n <= 10^4
  • 0 <= nums[i] <= n
  • All numbers in nums are unique.
ApproachTimeSpaceBest When
Hash SetO(n)O(n)Quick to write and easy to understand
Gauss SumO(n)O(1)Memory is constrained; elegant one-liner
  • Learn Gauss Sum first — it demonstrates a beautiful mathematical insight and is O(1) space.
  • Use Hash Set as a fallback if you forget the formula; it is correct and the same time complexity.
Elegant & Optimal
Gauss Sum
O(n) time · O(1) space
Easy to Remember
Hash Set
O(n) time · O(n) space
★ Recommended

The sum of all integers from 0 to n is given by the Gauss formula: n * (n + 1) / 2. Subtract the actual sum of nums from this expected total. The difference is precisely the missing number.

⏱ Time O(n) One pass to sum 💾 Space O(1) Two integer variables

Input: [3, 0, 1], n = 3

StepCalculationValue
Expected sum (0+1+2+3)3 × 4 / 26
Actual sum (3+0+1)3 + 0 + 14
Missing6 − 42

Animated walkthrough

How the Gauss formula pinpoints the missing number

Use Next or Autoplay to see the expected total computed, the actual sum accumulated, and the difference revealed.

Step 1 of 3
Waiting to begin...
Array state
Memory / lookup state

function missingNumber(nums):
n = len(nums)
expected = n * (n + 1) / 2
return expected - sum(nums)
missing_number_math.py
from typing import List
def missing_number(nums: List[int]) -> int:
n = len(nums)
expected = n * (n + 1) // 2
return expected - sum(nums)
print(missing_number([3, 0, 1])) # 2
print(missing_number([0, 1])) # 2
print(missing_number([9, 6, 4, 2, 3, 5, 7, 0, 1])) # 8
✓ Simple

Build a set from nums, then iterate 0 through n and return the first value that is not in the set.

⏱ Time O(n) Two passes 💾 Space O(n) Set stores n elements

Input: [3, 0, 1]

CheckIn set?
0Yes
1Yes
2No → return 2
function missingNumber(nums):
seen = set(nums)
for value in range(len(nums) + 1):
if value not in seen:
return value
missing_number_hash_set.py
from typing import List
def missing_number(nums: List[int]) -> int:
seen = set(nums)
for value in range(len(nums) + 1):
if value not in seen:
return value
return -1
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
missing_number_space_optimized.py
"""
Solution for Missing Number
"""
def solve():
"""Implementation for approach 3 of Missing Number"""
pass
if __name__ == "__main__":
print("Solution ready")