Missing Number
Array, Iterative Approach
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:
Example 2:
Example 3:
Constraints:
n == nums.length
1 <= n <= 104
0 <= nums[i] <= n
All the numbers of
nums
are unique.
Solutions
Approach - Brute Force Technique
This solution is considered a brute force approach because it checks each candidate number against all numbers in the array.
Steps
Outer Loop: The outer loop iterates over all numbers from 0 to
nums.Length
. Each number in this range is a potential candidate for the missing number.Inner Loop and Flag Initialization: For each candidate number, a boolean flag
found
is initialized tofalse
, and an inner loop iterates over all numbers in the arraynums
.Number Checking: Inside the inner loop, it checks if the current number in the array
nums
is equal to the candidate number. If it is, it setsfound
totrue
and breaks the inner loop.Missing Number Identification: After the inner loop, it checks the flag
found
. Iffound
is stillfalse
, it means the candidate number was not found in the arraynums
, so it returns the candidate number as the missing number.Completion: The function continues this process until it finds a missing number or it has checked all candidate numbers. If it has checked all candidate numbers and hasn’t found a missing number, it returns -1. However, according to the problem statement, there should always be one missing number, so this line should never be reached.
Complexity
Time Complexity: O(N^2)
Auxiliary Space: O(1)
Approach - Iterative Technique
Steps
Expected Sum Calculation: The function calculates the expected sum of all numbers from 0 to
nums.Length
using the formula for the sum of an arithmetic series:nums.Length*(nums.Length+1)/2
. This sum is stored inexpectedSum
.Actual Sum Calculation: The function then calculates the actual sum of all numbers in the array
nums
by iterating over each number innums
and adding it toactualSum
.Missing Number Calculation: Finally, the function calculates the missing number by subtracting
actualSum
fromexpectedSum
. The result is the number that is missing from the arraynums
.
Complexity
Time Complexity: O(N)
Auxiliary Space: O(1)
Last updated