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

Popular posts from this blog

Day 4 – Palindrome Number in JavaScript Without Converting to String

Day 9 – Count Vowels in a String using JavaScript | DSA Challenge with Code & Explanation

Day 13: Find Missing Number in an Array – JavaScript DSA Challenge