Given an array containing n distinct numbers taken from the range 0 to n, find the one number in that range that's missing from the array.
Video coming soon
We're producing a video walkthrough — check back soon.
Given an array containing n distinct numbers taken from the range 0 to n, find the one number in that range that's missing from the array.
The array's own indices secretly encode the answer here — this is the first problem in the course where index and value are two views of the same information, an idea Find All Duplicates and Find the Duplicate Number both build on later.
When a problem guarantees values fall inside a known range tied to the array's length (like 0..n or 1..n), think about what the array would look like if every index held its correct value — the mismatch is usually the answer.
Since nums holds n distinct values drawn from the (n+1)-value range [0, n], exactly one value from that range is missing. Compute the expected sum of 0..n using the closed-form formula n*(n+1)/2, subtract the array's actual sum, and the difference is the missing number. An XOR-based version avoids any risk of integer overflow on very large inputs by XOR-ing every index 0..n together with every array value — every present value cancels with its index pairing, leaving only the missing number.
class Solution {
public int missingNumber(int[] nums) {
int n = nums.length;
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
for (int num : nums) {
actualSum += num;
}
return expectedSum - actualSum;
}
}