Find the First K Missing Positive Numbers
Explore how to identify the first k missing positive integers in an unsorted array by leveraging cyclic sort. Understand how to handle negative numbers and zeros, and learn to extend your results with consecutive integers when needed. This lesson teaches you an optimal O(n + k) time approach with O(n) space to solve this common coding interview problem.
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.
import java.util.*;public class Solution{public static List<Integer> firstKMissingNumbers(int[] arr, int k) {// Replace this placeholder return statement with your codereturn new ArrayList<>();}}