educative.io

Educative

Alternate solution to missing number 2?

If we can assume that the sum total of all of the values in the array with the missing value is equal to the sum of all of the values of a full array minus the missing values couldn’t we take this approach? this would be time complexity O(n) and space complexity O(1). Am I missing something?

const find_missing_number = function(nums) {
  let partial = 0;
  let full = 0;
  for (let i = 0; i < nums.length; i++) {
partial += nums[i];
full += i;
if (i + 1 === nums.length) full += (i + 1);
  }

  if (partial === full) return -1;
  return full - partial;
};

Hello @Joseph_Foti

Your solution is also correct. There are multiple approaches and ways to solve any given problem.

Cheers!

This is good but I Think the reason this should be avoided is it could overflow easily, but the other solution should not.

Also why do you return -1 if full is equal to partial? Shouldn’t that mean 0 is missing?