01
Problem Statement
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range [0, n] that is missing from the array. There is exactly one missing number. n = nums.length, so the range has n+1 numbers and the array has n of them.
- Sum approach: The sum of
0 + 1 + ... + nisn*(n+1)/2. The sum ofnumsis missing exactly one number. So missing =n*(n+1)/2 - sum(nums). - XOR approach: XOR has the property that
x ^ x = 0. If we XOR all indices0..nand all values innums, every number that appears in both (index and value) cancels; the only number that appears once (the missing one, as an index) remains. Soxor = 0; foriin0..nxor^= i; forxinnumsxor^= x; returnxor.
02
Key Observations
- Sum:
expectedSum = n * (n + 1) / 2,actualSum = sum(nums), returnexpectedSum - actualSum. Watch for integer overflow for largen(use long or XOR). - XOR: Initialize
xor = 0. Forifrom 0 ton,xor ^= i. For eachxinnums,xor ^= x. Returnxor. No overflow issue.
03
Approach
High-level (Sum): n = nums.length, expectedSum = n * (n + 1) / 2, actualSum = sum of nums. Return expectedSum - actualSum.
Steps (XOR): n = nums.length, xor = 0. For i = 0..n: xor ^= i. For each x in nums: xor ^= x. Return xor.
04
Implementation
Java
public int missingNumber(int[] nums) {
int n = nums.length;
int expected = n * (n + 1) / 2;
int actual = 0;
for (int x : nums) {
actual += x;
}
return expected - actual;
}05
Test Cases
Example 1
Input
nums = [3,0,1]
Expected
2Explanation
n=3, range [0,3], 2 is missing.
06
Complexity Analysis
- Time: O(n).
- Space: O(1).
07
Follow-ups
- Find duplicate and missing (one duplicate, one missing in 1..n).