Missing Number LeetCode Question (Explained Simply)

Given an array of numbers, that are all distinct, return the only number in the range that is missing.

This question wants you to find the missing number in sequence of arrays, example:

let array = [1, 2, 3, 4, 6]

In the example above, the number we want to find is 5.

Steps

  • First, we must sort the numbers using pretty much any generic .sort() .
  • Then, we check to make sure 0 is at the beginning and that n is at the end.
  • Obtain array length and iterate through with a traditional for loop comparing against sorted array
var missingNumber = function(nums) {
    //Sort the array
    let sorted = nums.sort();
    //Iterate based on the length of the sorted array
    for(let i = 0; i <= nums.length; i++) {
        //Compare length and if number is not found return
        if(!sorted.includes(i)) return i
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *