A Step-by-Step Guide with Code Walk Through
In this Leetcode problem, we’re told that we’re given an ordered array of positive integers that has some missing numbers as input, along with a number (k). Our task: find the kth missing number in that input array. Sounds more complicated than it is. Let’s get at it.
Let’s say we have an array with the number [1, 2, 3, 4], and we’re told to find the 2nd missing number. Confusing. Doesn’t seem like there is a missing number in that array.
We’d have to assume that the two missing number are 5 and 6, and thus, the 2nd missing number is 6, and the full array would actually be [1, 2, 3, 4, 5, 6].
As a human, if you’re tasked to find the kth missing numbers in a sequence, I’d argue you’d do something like,
Let’s initialize a function called **findKthPositive **that takes in an array (arr) and a number (k) as input. And, as described above, we’re going to need to count how many numbers are missing in our sequence, so let’s initialize a missingCounter variable:
function findKthPositive(arr, k) {
let missingCounter = 0;
}
Next, we have to walk through our sequence. Let’s do that with a for loop. Typically we setup a for loop to run the entire length of an array. But what do we do when our array has missing values?
#leetcode #javascript