Problem
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.
Follow up: Could you implement a solution using only O(1)
extra space complexity and O(n)
runtime complexity?
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
We can use solutions like hashing
etc. But this problem has special numbers in array.
Video explanation
Here is the video explaining below methods in detail. Please check it out:
Method 1 - Using Sorting + linear search
A straightforward solution to this problem is to sort the array. When sorted, the numbers in the array should align with their respective indices since they range from 0
to n
. For example, take the array nums = [3, 0, 1]
. After sorting, it becomes nums = [0, 1, 3]
.
Once the array is sorted:
- Iterate through each element of the array and compare the value at each index with the index itself.
- If the value does not match its index, it indicates the missing number, which is the index.
If all numbers match their respective indices (e.g., nums = [0, 1, 2]
), it means the missing number is n+1, because no number is missing within the valid range [0, n]
. For example:
- Sorted array:
nums = [0, 1, 2]
, and the indices0, 1, 2
perfectly match the values in the array. - In this case, the missing number is the next number
3
, which isn+1
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
for sorting the array, and then traversing the array to check the mismatch takesO(n)
, overall:O(n log n)
. - 🧺 Space complexity:
O(1)
. Sorting the array may require additional space depending on the algorithm used, but we can assume constant space if we use in-place sorting algorithm likeQuicksort
.
Method 2 - Using Sorting + Binary Search
Once the array is sorted, we can optimise it further by using binary search, instead of performing a linear search. Binary search allows us to efficiently locate the missing number in the sorted array.
Here is the approach:
- Once the array
nums
is sorted, the missing number disrupts the sequence whereindex != nums[index]
. - Use binary search:
- Check at the middle index (
mid
) ifnums[mid] == mid
. - If they are equal, the missing number must be on the right half.
- If they are not equal, the missing number must be on the left half.
- Check at the middle index (
- Continue narrowing down to find the missing index.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
for sorting andO(log n)
for finding missing element. OverallO(n log n)
- 🧺 Space complexity:
O(n)
Method 3 - Using Hashset
A more effective approach to track the presence of elements is to use hashset. In hashset, we can insert and look up an element in just O(1)
time. So, we add all the numbers from the array into a hashset and then verify which numbers in the range [0, n]
(from 0 to n) are missing in the hashset.
For e.g. for this array, nums = [3,0,1]
, we add all elements to hashset hashset = {3, 0, 1}
. Now, we iterate through the range [0, n]
(where n = 3
) and check which numbers are missing:
0
is in the HashSet ✅.1
is in the HashSet ✅.2
is not in the HashSet ❌ ⇨ the missing number is2
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(n)
Method 4 - Using Arithmetic Sum
Here is the approach:
- Calculate the sum of the range
[0, n]
using the formula. - Sum up all the elements in the array.
- Subtract the sum of the array from the sum of the range to get the missing number.
Method 5 - Using Arithmetic sum + Gaussian formula
This is a mathematical optimisation of the arithmetic sum approach where we explicitly rely on the Gaussian formula, simplifying the calculation further: $$ \text{sum of range} = \frac{n \times (n+1)}{2} $$
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)
Method 6 - Using Arithmetic sum but avoid overflow
Large values of n
can produce sums exceeding the integer limits, potentially causing overflow issues. We avoid this by summing numbers iteratively or simply calculating the difference directly during array traversal.
Here is the approach:
- Instead of computing full sums, iterate and calculate the difference between each index in
[0, n]
and the corresponding array value. - Add the last index (
n
) in the range after completing the traversal. - This avoids creating large sums altogether, preventing overflow.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)
Method 7 - Using XOR Operator
We know the following properties of XOR:
x ^ x = 0
(cancels identical numbers).x ^ 0 = x
(preserves a number when XORed with 0). All numbers XORed together, including the range[0, n]
and elements of the array, will cancel out except for the missing number.
Approach
- XOR all numbers in the range
[0, n]
. - XOR all numbers in the array.
- Combine the two XOR results to get the missing number (remaining unmatched due to cancellation).
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)