268. Missing Number - Explanation
Description
Given an array nums containing n integers in the range [0, n] without any duplicates, return the single number in the range that is missing from nums.
Follow-up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?
Example 1:
Input: nums = [1,2,3]
Output: 0Explanation: Since there are 3 numbers, the range is [0,3]. The missing number is 0 since it does not appear in nums.
Example 2:
Input: nums = [0,2]
Output: 1Constraints:
1 <= nums.length <= 1000
Topics
Recommended Time & Space Complexity
You should aim for a solution with O(n) time and O(1) space, where n is the size of the input array.
Hint 1
A brute force approach would iterate through the range of numbers from 0 to n, checking if each number is present in the given array. If a number is missing, it is returned. This results in an O(n^2) solution. Can you think of a better way? Maybe a data structure could help optimize this process.
Hint 2
We can use a hash set by inserting the given array elements into it. Then, we iterate through the range of numbers from 0 to n and use the hash set for O(1) lookups to find the missing number. Can you think of a way to further optimize this? Maybe a bitwise operator could be useful.
Hint 3
We can use bitwise XOR. When two identical numbers are XORed, the result is 0. Using this property, we can efficiently find the missing number.
Hint 4
We first compute the bitwise XOR of numbers from 0 to n. Then, we iterate through the array and XOR its elements as well. The missing number remains in the final XOR result since all other numbers appear twice—once in the range and once in the array—while the missing number is XORed only once.
Prerequisites
Before attempting this problem, you should be comfortable with:
- Bitwise XOR - The XOR approach uses the property that a number XORed with itself equals zero to cancel out all present numbers
- Math (Sum Formula) - The mathematical approach uses the sum formula for consecutive integers to find the missing value
- Hash Set - One solution uses constant-time lookups to identify which number from the expected range is absent
1. Sorting
Intuition
We are given an array containing n distinct numbers taken from the range [0, n].
Exactly one number is missing, and we need to find it.
A simple way to reason about this is:
- If the array were complete and sorted, the number at index
ishould be exactlyi - As soon as this condition breaks, that index represents the missing number
Sorting the array puts the numbers in order, making this comparison straightforward and beginner-friendly.
Algorithm
- Sort the array in ascending order.
- Traverse the array from index
0ton - 1:- If
nums[i] != i, theniis the missing number → returni.
- If
- If all indices match their values:
- The missing number must be
n→ returnnas the result.
- The missing number must be
Time & Space Complexity
- Time complexity:
- Space complexity: or depending on the sorting algorithm.
2. Hash Set
Intuition
We are given n distinct numbers taken from the range [0, n], with exactly one number missing.
A natural way to approach this is to ask:
“Can we quickly check whether a number exists in the array?”
Using a hash-based data structure (like a hash set) allows us to:
- Store all given numbers
- Check the presence of any number in constant time
Once all numbers are stored, we simply look for the number in the range [0, n] that does not appear in the set.
This approach trades a little extra space for very clear and simple logic.
Algorithm
- Insert all elements of the array into a hash set.
- Iterate through all numbers from
0ton:- If a number is not present in the set, return it as the missing number.
- Since exactly one number is missing, this process will always find the answer.
Time & Space Complexity
- Time complexity:
- Space complexity:
3. Bitwise XOR
Intuition
We are given n distinct numbers from the range [0, n], with exactly one number missing.
A very powerful observation comes from the properties of XOR (⊕):
a ⊕ a = 0(a number cancels itself)a ⊕ 0 = a- XOR is commutative and associative (order does not matter)
If we XOR:
- all numbers from
0ton - and all numbers present in the array
Every number that appears in both places will cancel out, leaving only the missing number.
This allows us to find the answer in linear time and constant space, without sorting or extra data structures.
Algorithm
- Let
nbe the length of the array. - Initialize a variable
xorrwithn. - For each index
ifrom0ton - 1:- XOR
xorrwithi - XOR
xorrwithnums[i]
- XOR
- After the loop,
xorrwill contain the missing number. - Return
xorr.
Time & Space Complexity
- Time complexity:
- Space complexity:
4. Math
Intuition
We are given n distinct numbers from the range [0, n], with exactly one number missing.
A simple mathematical observation helps here:
- The sum of numbers from
0tonis known - If we subtract the sum of the given array from this expected sum, the result must be the missing number
Instead of computing two separate sums, we can combine both ideas into a single running calculation, which keeps the logic clean and avoids overflow issues in some languages.
This approach uses basic arithmetic, making it easy to understand and language-independent.
Algorithm
- Let
nbe the length of the array. - Initialize a variable
res = n. - For each index
ifrom0ton - 1:- Add
itores - Subtract
nums[i]fromres
- Add
- After the loop,
reswill hold the missing number. - Return
resas the answer.
Time & Space Complexity
- Time complexity:
- Space complexity:
Common Pitfalls
Forgetting That n Could Be the Missing Number
The range is [0, n] for an array of length n, meaning n itself could be missing. Solutions that only check indices 0 to n-1 will miss this case and fail to return n when all other numbers are present.
Integer Overflow in Sum-Based Approach
When using the mathematical approach, computing the full expected sum n * (n + 1) / 2 separately before subtracting can cause overflow for large n. Combining addition and subtraction in a single loop avoids this issue.
Sign in to join the discussion