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 - Hash Set Approach INPUT Array: nums = [3, 0, 1] 3 idx 0 0 idx 1 1 idx 2 n = 3 (array length) Range: [0, 3] Expected Numbers: 0 1 2 3 Red = Missing! ALGORITHM STEPS 1 Create Hash Set Add all nums to set {0, 1, 3} 2 Check Range [0,n] Loop i from 0 to 3 3 Set Lookup Check if i in set i | in set? 0 OK 1 OK 2 NO! 3 OK 4 Return Missing 2 not in set! FINAL RESULT The missing number is: 2 Output: 2 Verification: Array has: 0, 1, 3 Range [0,3] needs: 0,1,2,3 Time: O(n) | Space: O(n) Key Insight: Hash Set provides O(1) lookup time. By storing all array elements in a set, we can check each number from 0 to n in constant time. The first number not found in the set is our answer. TutorialsPoint - Missing Number | Hash Set Approach
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