JavaScript DSA – Find the Missing Number in an Array
๐ Problem Statement:
> You are given an array containing n distinct numbers taken from 1 to n+1. One number is missing. Find it efficiently using JS.
๐ก Solution:
function findMissingNumber(arr) {
const n = arr.length + 1;
const expectedSum = (n * (n + 1)) / 2;
const actualSum = arr.reduce((acc, num) => acc + num, 0);
return expectedSum - actualSum;
}
console.log(findMissingNumber([1, 2, 4, 5, 6])); // Output: 3
๐ง Explanation:
We know the sum of 1 to n is n*(n+1)/2.
Subtracting the actual sum from this gives the missing number.
This approach is better than nested loops or sorting.
---
✅ Bonus Tip:
> Use .reduce() in JS for summing values in arrays. It’s a commonly asked method in interviews!
---
✅ Try It Yourself:
What if 2 numbers are missing?
How to solve it without extra space?
---
๐ข Engage:
Share your variation in the comments.
Follow the Code With Jaffer Blog for daily tips!
Comments
Post a Comment