Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding missing element in an array of numbers in JavaScript
We are required to write a JavaScript function that takes in an array of numbers of length, say n. The array contains all the integers from 0 to n (including both 0 and n), but just one integer is missing, it can be any number and the array is not sorted. The task of our function is to find the missing number and return it in linear time and constant space.
Since the array contains all the numbers from 0 to n but one, we can simply calculate the sum of all the elements of the array in linear time. Then we can subtract it from the sum of first n natural numbers which can be calculated in constant time and space. The difference between the both will be our missing number.
How It Works
The algorithm uses the mathematical formula for the sum of first n natural numbers: n × (n + 1) / 2. We calculate the expected sum and subtract the actual sum of array elements to find the missing number.
Example
Following is the code ?
const arr = [3, 7, 8, 10, 11, 0, 2, 6, 1, 4, 5];
const findMissing = (arr = []) => {
const sum = arr.reduce((acc, val) => acc + val);
const { length: num } = arr;
const correctSum = (num * (num + 1)) / 2;
const diff = correctSum - sum;
return diff;
};
console.log(findMissing(arr));
Output
Following is the console output ?
9
Step-by-Step Breakdown
const arr = [3, 7, 8, 10, 11, 0, 2, 6, 1, 4, 5];
console.log("Array length:", arr.length);
console.log("Expected range: 0 to", arr.length);
const actualSum = arr.reduce((acc, val) => acc + val);
console.log("Actual sum:", actualSum);
const expectedSum = (arr.length * (arr.length + 1)) / 2;
console.log("Expected sum:", expectedSum);
const missing = expectedSum - actualSum;
console.log("Missing number:", missing);
Array length: 11 Expected range: 0 to 11 Actual sum: 57 Expected sum: 66 Missing number: 9
Alternative Approach Using XOR
Another efficient method uses the XOR operation, which has the property that a ^ a = 0 and a ^ 0 = a:
const findMissingXOR = (arr = []) => {
let xorAll = 0;
let xorArray = 0;
// XOR all numbers from 0 to n
for (let i = 0; i <= arr.length; i++) {
xorAll ^= i;
}
// XOR all array elements
for (let num of arr) {
xorArray ^= num;
}
return xorAll ^ xorArray;
};
const testArray = [0, 1, 3, 4, 5];
console.log("Missing number using XOR:", findMissingXOR(testArray));
Missing number using XOR: 2
Comparison
| Method | Time Complexity | Space Complexity | Overflow Risk |
|---|---|---|---|
| Sum Formula | O(n) | O(1) | Yes (for large numbers) |
| XOR Operation | O(n) | O(1) | No |
Conclusion
Both approaches efficiently find the missing number in O(n) time and O(1) space. The sum-based method is more intuitive, while XOR avoids potential integer overflow issues with very large arrays.
