Missing Number

EASY

Given an array nums containing n distinct numbers taken from the range 0, 1, 2, ..., n, find the one number in that range that is missing from the array.

Examples:

Example 1:

Input: nums = [3, 0, 1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so the range is [0,3]. 2 is the missing number.

Example 2:

Input: nums = [0, 1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so the range is [0,2]. 2 is the missing number.

Example 3:

Input: nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]
Output: 8
Explanation: n = 9 since there are 9 numbers, so the range is [0,9]. 8 is the missing number.

Example 4:

Input: nums = [0]
Output: 1
Explanation: n = 1 since there is 1 number, so the range is [0,1]. 1 is the missing number.

Constraints:

  • n == nums.length
  • 1 <= n <= 104
  • 0 <= nums[i] <= n
  • All the numbers of nums are unique.

Function Signature (Python):

from typing import List

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        # Your code here
        pass

 

Nerchuko Academy · Free DS Interview Prep