Search⌘ K
AI Features

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.

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:

  • n=n = arr.length

  • 1k1041 \leq k \leq 10^4

  • 104-10^4 \leq arr[i] 104\leq 10^4

  • 0n1040 \leq n \leq 10^4

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 KK Missing Positive Numbers

1.

What could be the correct output if the following values are given as input?

array = [1, 2, 3, 0, 4, 9, 7]
k = 4

A.

[5, 6, 8, 9]

B.

[5, 6, 7, 10]

C.

[5, 6, 8, 10]


1 / 3

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.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

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.

Java
usercode > Solution.java
import java.util.*;
public class Solution{
public static List<Integer> firstKMissingNumbers(int[] arr, int k) {
// Replace this placeholder return statement with your code
return new ArrayList<>();
}
}
Find the First K Missing Positive Numbers