Missing Number easy

Problem Statement

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.

Example 1:

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

Example 2:

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

Steps

  1. Calculate the expected sum: The sum of numbers from 0 to n is given by the formula n(n+1)/2.
  2. Calculate the actual sum: Sum all the numbers present in the input array nums.
  3. Find the difference: Subtract the actual sum from the expected sum. The difference will be the missing number.

Explanation

The approach leverages the mathematical property of arithmetic series. We know the expected sum of numbers from 0 to n. By calculating the actual sum of the numbers present in the array and comparing it to the expected sum, we can easily identify the missing number. This method is efficient because it avoids iterating through the array multiple times.

Code

def missingNumber(nums):
    """
    Finds the missing number in an array of numbers from 0 to n.

    Args:
        nums: A list of integers.

    Returns:
        The missing number.
    """
    n = len(nums)
    expected_sum = n * (n + 1) // 2  # Integer division to avoid floating-point numbers
    actual_sum = sum(nums)
    return expected_sum - actual_sum

Complexity

  • Time Complexity: O(n), as we iterate through the nums array once to calculate the sum.
  • Space Complexity: O(1), as we only use a few constant extra variables.