An array contains n distinct numbers from the range 0..n (so one is missing). Find the missing number.
The O(n) O(1)-space trick uses the sum formula: expected sum of 0..n is n*(n+1)/2; subtract the actual array sum to get the missing number. XOR is an overflow-safe alternative.
function missingNumber(nums) {
const n = nums.length;
const expected = (n * (n + 1)) / 2;
const actual = nums.reduce((a, b) => a + b, 0);
return expected - actual;
}The sum/XOR trick appears in reconciling sequence gaps — e.g. detecting a missing page number or a dropped message id in a stream.
For very large n the sum approach gives a slightly wrong answer. What is the risk and the safer alternative?