Find Missing Number
Given an array nums containing n distinct numbers taken from the range 0 to n, find the one number that is missing from the range. Each number appears exactly once except the missing one.
Use the sum formula approach: the expected sum of numbers from 0 to n is n * (n + 1) / 2. Compute the actual sum of all elements in the array using a loop. The difference between the expected and actual sum is the missing number.
This problem can also be solved using XOR: XOR all array elements together with all numbers from 0 to n. The result is the missing number since XOR of a number with itself cancels out, leaving only the unpaired element.
Edge cases include an array with [0] (missing 1), an array with [1] (missing 0), and arrays where the missing number is n (the largest number in the range).
TypeScript's type system ensures the function handles number arrays correctly. The time complexity is O(n) with O(1) space using the formula approach. The subtraction method works for the constraints where n*(n+1)/2 fits within the number range.
The sum formula relies on the mathematical identity that the sum of integers from 0 to n is n(n+1)/2. This formula was discovered by Carl Friedrich Gauss as a schoolchild and is a foundational result in arithmetic series.Example Input & Output
Algorithm Flow

Solution Approach
Given an array nums containing n distinct numbers taken from the range 0 to n, find the one number that is missing from the range. Each number appears exactly once except the missing one.
Use the sum formula approach: the expected sum of numbers from 0 to n is n * (n + 1) / 2. Compute the actual sum of all elements in the array using a loop. The difference between the expected and actual sum is the missing number.
This problem can also be solved using XOR: XOR all array elements together with all numbers from 0 to n. The result is the missing number since XOR of a number with itself cancels out, leaving only the unpaired element.
Edge cases include an array with [0] (missing 1), an array with [1] (missing 0), and arrays where the missing number is n (the largest number in the range).
TypeScript's type system ensures the function handles number arrays correctly. The time complexity is O(n) with O(1) space using the formula approach. The subtraction method works for the constraints where n*(n+1)/2 fits within the number range.
Best Answers
function findMissingNumber(nums: number[]): number {
var n = nums.length;
var expected = n * (n + 1) / 2;
var actual = 0;
for (var i = 0; i < nums.length; i++) {
actual += nums[i];
}
return expected - actual;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
