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.

Note: The array contains exactly n numbers, where each number is unique and falls within the range [0, n]. Your task is to find the single missing number.

Input & Output

Example 1 — Basic Missing Number
$ Input: nums = [3,0,1]
Output: 2
💡 Note: Array has numbers [3,0,1] from range [0,3]. The missing number is 2.
Example 2 — Missing First Number
$ Input: nums = [0,1]
Output: 2
💡 Note: Array has numbers [0,1] from range [0,2]. The missing number is 2.
Example 3 — Missing Zero
$ Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
💡 Note: Array has 9 numbers from range [0,9]. After checking, 8 is missing.

Constraints

  • n == nums.length
  • 1 ≤ n ≤ 104
  • 0 ≤ nums[i] ≤ n
  • All numbers in nums are unique

Visualization

Tap to expand
Missing Number Problem: Array [3,0,1] from Range [0,3]Input Array:301Expected Range [0,3]:0123Missing!Output: 2 (the missing number)
Understanding the Visualization
1
Input
Array with n distinct numbers from range [0,n]
2
Process
Find which number from 0 to n is not present
3
Output
Return the missing number
Key Takeaway
🎯 Key Insight: Use mathematical sum formula or XOR properties to find missing number in O(n) time and O(1) space
Asked in
Microsoft 45 Amazon 38 Google 32 Apple 28
307.6K Views
High Frequency
~15 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen