Find the First K Missing Positive Numbers
Explore how to find the first k missing positive integers from an unsorted array, excluding negatives and zeroes, by applying the cyclic sort pattern. This lesson helps you understand and implement an optimal O(n + k) time solution, enabling you to tackle similar interview problems with confidence.
We'll cover the following...
Statement
Given an unsorted integer array, arr, of size n and an integer k, find the first k missing positive integers from the array, ignoring all negative numbers and zeros.
If the array does not contain enough missing positive numbers, add the next consecutive positive integers, starting from the smallest number greater than the largest value in the array, until exactly k missing positive numbers have been found.
Return the list of the first k missing positive integers, sorted in ascending order.
Constraints:
arr.lengtharr[i]
Examples
Understanding the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Find the First Missing Positive Numbers
What could be the correct output if the following values are given as input?
array = [1, 2, 3, 0, 4, 9, 7]
k = 4
[5, 6, 8, 9]
[5, 6, 7, 10]
[5, 6, 8, 10]
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Note: As an additional challenge, we have intentionally hidden the solution to this puzzle.
Try it yourself
Implement your solution in the following coding playground:
We have left the solution to this challenge as an exercise for you. The optimal solution to this problem runs in O(n + k) time and takes O(n) space. You may try to translate the logic of the solved puzzle into a coded solution.
package mainfunc firstKMissingNumbers(arr []int, k int) []int{// Replace this placeholder return statement with your codereturn make([]int, 0)}