← Back to libraryQuestion 160 of 468
🧩JavaScript CodingIntermediate

Find the Missing Number

📌 Definition:

An array contains n distinct numbers from the range 0..n (so one is missing). Find the missing number.

📖 Detailed Explanation:

The O(n) O(1)-space trick uses the sum formula: expected sum of 0..n is n*(n+1)/2; subtract the actual array sum to get the missing number. XOR is an overflow-safe alternative.

💻 Solutions:
function missingNumber(nums) {
  const n = nums.length;
  const expected = (n * (n + 1)) / 2;
  const actual = nums.reduce((a, b) => a + b, 0);
  return expected - actual;
}
🔑 Key Points:
  • Sum formula n*(n+1)/2 minus actual sum → missing
  • O(n) time, O(1) space
  • XOR approach avoids large-number overflow
  • Works because numbers are distinct and from a known range
🌍 Real-World Example:

The sum/XOR trick appears in reconciling sequence gaps — e.g. detecting a missing page number or a dropped message id in a stream.

🎯 Scenario-Based Interview Question:

For very large n the sum approach gives a slightly wrong answer. What is the risk and the safer alternative?