Taro Logo

Missing Number

#89 Most AskedEasy
Topics:
Arrays

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.

Example 3:

Input: nums = [9,6,4,2,3,5,7,0,1]

Output: 8

Explanation:

n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.

 
 

 

 

Constraints:

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

Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected range of the sequence? Does it always start from 0 (or 1), or could it be an arbitrary range like from `n` to `m`?
  2. Are there any duplicate values in the input array, or are all elements guaranteed to be distinct as stated in the problem description?
  3. Could the input array be empty or contain only a single element, and if so, what is the expected output for those edge cases?
  4. Can the input array contain negative numbers, or are we strictly dealing with non-negative integers?
  5. Is the input array guaranteed to be sorted, or should I assume it is in random order?

Brute Force Solution

Approach

Imagine you are given a complete sequence of numbers from a starting value up to a target ending value, but one of the numbers is missing. The brute force approach involves going through the full set of expected numbers one by one and checking if each individual number is present in the collection you were given.

Here's how the algorithm would work step-by-step:

  1. Begin with the smallest possible number in the expected sequence.
  2. Look through your entire collection of numbers to see if this number is present.
  3. If you check the whole collection and find that this number is missing, you have found your answer.
  4. If the number is present, move on to the very next number in the expected sequence.
  5. Repeat this checking process for every single number in the complete sequence until you find the one that is missing.

Code Implementation

def find_missing_number_brute_force(given_numbers):
    expected_minimum = 0
    expected_maximum = len(given_numbers)

    # Iterate through the complete sequence of expected numbers from minimum to maximum
    for current_number in range(expected_minimum, expected_maximum + 1):
        
        is_number_found = False
        
        # Search the entire collection to determine if the current expected number is present
        for element in given_numbers:
            if element == current_number:
                is_number_found = True
                break

        # Return immediately if the expected number is absent from the given collection
        if not is_number_found:
            return current_number

    return -1

Big(O) Analysis

Time Complexity
O(n²) – The brute force strategy iterates through every expected number from the starting value up to the target ending value, resulting in roughly n iterations. For each of these expected numbers, the algorithm scans through the entire collection of n elements to see if it is present. This means we perform a complete scan of the collection for every single expected number, leading to approximately n * n operations. Dropping the constant factor, this nested checking process simplifies to a total runtime of O(n²).
Space Complexity
O(1) – The brute force approach described only utilizes a few primitive scalar variables, such as loop counters and flags, to check each expected number against the collection. No auxiliary data structures like temporary lists or hash maps are created during the execution. Since these few variables consume a constant amount of extra memory regardless of the input size N, the auxiliary space complexity remains strictly constant.

Optimal Solution

Approach

Instead of checking every single item one by one to find the missing piece, we can use a clever mathematical shortcut. By knowing the total expected sum of a complete sequence, we can simply find the sum of what we currently have and see what is missing to make up the difference.

Here's how the algorithm would work step-by-step:

  1. Figure out what the total sum should be if no numbers were missing at all, based on the highest value in the sequence.
  2. Add up all the numbers that are currently present in front of you.
  3. Compare the complete expected total with the sum of the numbers you actually have.
  4. The difference between the expected total and your current sum reveals the exact value that was left out.

Code Implementation

def find_missing_number(sequence_numbers):
    highest_sequence_value = len(sequence_numbers)

    # We calculate the expected sum using the standard arithmetic progression formula to find the complete total.
    expected_total_sum = highest_sequence_value * (highest_sequence_value + 1) // 2

    current_actual_sum = sum(sequence_numbers)

    # The missing value is precisely the gap between what the sum should be and what it actually is.
    return expected_total_sum - current_actual_sum

Big(O) Analysis

Time Complexity
O(n) – The cost of the algorithm is driven by the single pass required to add up all the numbers currently present in the array of size n. Calculating the expected total sum takes constant time using the arithmetic progression formula n * (n + 1) / 2 without needing additional loops. Comparing the expected total with the actual sum also takes constant time. Thus, the total operations scale linearly as n increases, which simplifies to O(n).
Space Complexity
O(1) – The algorithm only uses a few primitive variables to store the expected sum and the current running sum of the sequence. These scalar variables consume a constant amount of memory regardless of the input size N. Since no additional data structures like arrays or hash maps scale with N, the auxiliary space complexity remains strictly constant.

Edge Cases

Empty or null input array
How to Handle:
Return zero or throw an appropriate argument exception based on the function signature contract.
Minimum sized input array with a single element
How to Handle:
Compare the single element against the expected range to immediately deduce the missing number.
Maximum sized input array approaching system memory limits
How to Handle:
Use the mathematical sum formula approach to operate in O(1) space complexity and avoid allocation overhead.
Integer overflow during sum calculation
How to Handle:
Cast the array elements and range bounds to 64-bit integers before computing the arithmetic progression sum.
The missing number is at the very beginning of the range
How to Handle:
The expected sum will exceed the actual sum by the exact value of the starting boundary, which is zero.
The missing number is at the very end of the range
How to Handle:
The mathematical sum formula naturally accounts for the upper bound and correctly isolates the missing upper value.
Input sequence starts from a non-zero number
How to Handle:
Apply a generalized arithmetic sum formula that incorporates the minimum value offset of the sequence range.
0/245 completed