# Missing Number

Given an array containing n distinct numbers taken from `0, 1, 2, ..., n`, find the one that is missing from the array.

Example 1:
Input: [3,0,1] Output: 2

Example 2:
Input: [9,6,4,2,3,5,7,0,1] Output: 8

``````var missingNumber = function(nums) {
// Go through the array, at each index, boolean to new array
let max = 0
let sum = 0
// Go through array
for (let i=0; i<nums.length; i++){
sum += nums[i]
}

let target = ((nums.length)*(nums.length+1))/2
return target - sum
};``````

Approach:
Loop through the array, find the max, then see if any of the integers are missing.

Code Breakdown:
Let’s go through the relevant sections of the code block by block.

``````  for (let i=0; i<nums.length; i++){
sum += nums[i]
}``````

What this does is goes through each element of the array starting from zero, and adds the element to the sum.
Sum thus becomes the total of all the elements of the array.

``````  let target = ((nums.length)*(nums.length+1))/2
return target - sum``````

This is a bit mathematical so let’s explain it.
We set target equal to what the sum of the numbers should be if no numbers were missing.
If no numbers were missing, we’d be summing up length+1 elements, since length is the elements we have, and we add 1 for the missing one. Let’s keep this thought for a moment because it’ll come in handy.
The sum of consecutive numbers 1,2,3,…,n is (n)*(n+1)/2. That’s just a mathematical formula I remember from freshman year of college math class. However, we start from 0 here so the first element doesn’t do anything. We can adjust that formula, or we can adjust the input n. Normally n would be nums.length and for n+1 elements we’d need nums.length+1. However since the first element is zero, length can be seen as overstated by 1. So therefore we just use length instead of length+1 to get the sum of n+1 elements.
Finally, the difference between the target sum of n+1 elements (if no element was missing) and the actual sum, is our missing number.