Search⌘ K
AI Features

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.

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. 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.

Python
usercode > main.py
def first_k_missing_numbers(arr, k):
# Replace this placeholder return statement with your code
return []
Find the First K Missing Positive Numbers