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

๐Ÿ”” Day 13: Find Missing Number in an Array – JavaScript DSA

Welcome to #Day13 of the CodeWithJaffer DSA series!

๐Ÿ“Œ Problem:

Given an array containing numbers from 0 to n with one number missing, find that missing number.

๐Ÿงช Examples:


Input: [3, 0, 1]

Output: 2

Input: [0, 1, 2, 4, 5]

Output: 3

✅ JavaScript Code:



function findMissingNumber(arr) {

  const n = arr.length;

  const total = (n * (n + 1)) / 2;

  const sum = arr.reduce((acc, curr) => acc + curr, 0);

  return total - sum;

}

console.log(findMissingNumber([3, 0, 1]));       // 2

console.log(findMissingNumber([0, 1, 2, 4, 5])); // 3

๐Ÿ’ก Tips:

  • Use math formula for sum: n(n+1)/2
  • Reduce method calculates actual sum
  • Subtract to get missing number

๐ŸŽฏ Bonus:

Try solving with XOR approach too – it’s commonly asked in interviews!

๐Ÿ”— Follow me for more:

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