JavaScript Program to Find Missing Number in Array
n * (n + 1) / 2 and subtracting the actual sum of the array using const missing = totalSum - actualSum;.Examples
How to Think About It
n * (n + 1) / 2. Then, add all numbers in the given array. The difference between these two sums is the missing number.Algorithm
Code
function findMissingNumber(arr) { const n = arr.length + 1; const totalSum = (n * (n + 1)) / 2; const actualSum = arr.reduce((sum, num) => sum + num, 0); return totalSum - actualSum; } const array = [1, 2, 4, 5, 6]; console.log(findMissingNumber(array));
Dry Run
Let's trace the array [1, 2, 4, 5, 6] through the code to find the missing number.
Calculate n
Array length is 5, so n = 5 + 1 = 6.
Calculate totalSum
totalSum = 6 * (6 + 1) / 2 = 6 * 7 / 2 = 21.
Calculate actualSum
Sum of array elements = 1 + 2 + 4 + 5 + 6 = 18.
Find missing number
missing = totalSum - actualSum = 21 - 18 = 3.
| Step | Value |
|---|---|
| n | 6 |
| totalSum | 21 |
| actualSum | 18 |
| missing | 3 |
Why This Works
Step 1: Calculate expected sum
Using the formula n * (n + 1) / 2 gives the sum of all numbers from 1 to n, which is what the array should have if no number was missing.
Step 2: Sum actual array values
Adding all numbers in the array shows what is actually present.
Step 3: Subtract to find missing
The difference between expected and actual sums reveals the missing number because that value was not added in the actual sum.
Alternative Approaches
function findMissingNumberSet(arr) { const n = arr.length + 1; const set = new Set(arr); for (let i = 1; i <= n; i++) { if (!set.has(i)) return i; } } console.log(findMissingNumberSet([1, 2, 4, 5, 6]));
function findMissingNumberSort(arr) { arr.sort((a, b) => a - b); for (let i = 0; i < arr.length; i++) { if (arr[i] !== i + 1) return i + 1; } return arr.length + 1; } console.log(findMissingNumberSort([1, 2, 4, 5, 6]));
Complexity: O(n) time, O(1) space
Time Complexity
Calculating the sum and iterating once over the array takes linear time, O(n).
Space Complexity
Only a few variables are used, so space complexity is constant, O(1).
Which Approach is Fastest?
The sum formula approach is fastest and uses least memory compared to set or sorting methods.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sum formula | O(n) | O(1) | Fastest and memory efficient |
| Set method | O(n) | O(n) | Easy to understand, works with unsorted arrays |
| Sorting method | O(n log n) | O(1) | When array needs sorting anyway |