Overview
Given an array containing n distinct numbers taken from the range 0 to n, find the one number that is missing from the array.
Implement findMissing(nums).
Constraints
- Input is an array of
ndistinct integers in the range[0, n]. - Exactly one number in the range is missing.
- The array is not necessarily sorted.
- Aim for $O(n)$ time and $O(1)$ extra space.
Examples
findMissing([3, 0, 1]); // 2 findMissing([0, 1]); // 2 findMissing([9, 6, 4, 2, 3, 5, 7, 0, 1]); // 8 findMissing([0]); // 1
Notes
- The Gauss formula approach: the sum of
0..nisn*(n+1)/2. Subtract the actual sum of the array to find the missing value. - An XOR-based approach also works in $O(1)$ space: XOR all numbers
0..nwith all array values — the result is the missing number. - Beware of overflow with very large arrays if using the sum approach (not a concern in JS with
Number, but good to know).
Solution
Reveal solution
function findMissing(nums) {
const n = nums.length;
const expectedSum = (n * (n + 1)) / 2;
const actualSum = nums.reduce((sum, v) => sum + v, 0);
return expectedSum - actualSum;
}Resources
find-missing-number.js
Find Missing Number in Sequence
hardcodingAlgorithmsData Structures
Overview
Given an array containing n distinct numbers taken from the range 0 to n, find the one number that is missing from the array.
Implement findMissing(nums).
Constraints
- Input is an array of
ndistinct integers in the range[0, n]. - Exactly one number in the range is missing.
- The array is not necessarily sorted.
- Aim for $O(n)$ time and $O(1)$ extra space.
Examples
findMissing([3, 0, 1]); // 2 findMissing([0, 1]); // 2 findMissing([9, 6, 4, 2, 3, 5, 7, 0, 1]); // 8 findMissing([0]); // 1
Notes
- The Gauss formula approach: the sum of
0..nisn*(n+1)/2. Subtract the actual sum of the array to find the missing value. - An XOR-based approach also works in $O(1)$ space: XOR all numbers
0..nwith all array values — the result is the missing number. - Beware of overflow with very large arrays if using the sum approach (not a concern in JS with
Number, but good to know).
Solution
Reveal solution
function findMissing(nums) {
const n = nums.length;
const expectedSum = (n * (n + 1)) / 2;
const actualSum = nums.reduce((sum, v) => sum + v, 0);
return expectedSum - actualSum;
}Resources
NameTopicDifficulty
103 of 103 problems