Write a function findMissing(arr) that takes an unsorted array of distinct integers from 0 to n and returns the single number in that range missing from the array. For example, findMissing([3, 0, 1]) should return 2, and findMissing([0, 1, 2, 4, 5]) should return 3.
function findMissing(arr) {
// your code here
}
Rules:
The input array contains distinct integers from 0 to n with exactly one value missing.
Do not use external libraries.
Return the single missing integer.
Post your solution as a reply. Answer goes up in about a day.
Challenge solution: The challenge asks to find the single missing number in an unsorted array of distinct integers from 0 to n.
One way to do it:
function findMissing(arr) {
const n = arr.length;
const expectedSum = n * (n + 1) / 2;
let actualSum = 0;
for (let i = 0; i < n; i++) {
actualSum += arr[i];
}
return expectedSum - actualSum;
}
Why:
This solution leverages the mathematical property that the sum of integers from 0 to n can be calculated directly using the formula n * (n + 1) / 2. By calculating the expected sum and subtracting the actual sum of the elements present in the array, the difference reveals the single missing number. This approach is efficient as it involves a single pass through the array and constant time arithmetic operations.
The XOR approach is elegant for its constant space complexity, assuming no duplicates. But the interesting question for me is always what happens when constraints change a little. Like if the numbers aren’t strictly sequential.