Find the First K Missing Positive Numbers
Explore how to identify the first k missing positive numbers from an unsorted integer array by applying cyclic sort. Understand constraints and implement an optimal solution running in O(n + k) time with O(k) space, preparing you for coding interviews.
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. An optimal solution to this problem runs in O(n + k) time and takes O(k) space. You may try to translate the logic of the solved puzzle into a coded solution.
def first_k_missing_numbers(arr, k):# Replace this placeholder return statement with your codereturn []