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= arr.length
1≤k≤104 −104≤ arr[i]
≤104 0≤n≤104
Solution
The cyclic sort algorithm efficiently finds the first
After rearranging the array, any index
The steps of the algorithm are as follows:
Initialize a result list,
missing_nums
, to store missing numbers and a set,extra_nums
, to track duplicate or extra numbers. Also, initializen
with the length of the array.Apply cyclic sort to place elements in their correct positions. For each element
arr[i]
in the array:If
arr[i]
is within the valid range (1
ton
) and not already in its correct position (i.e.,arr[i] != arr[arr[i] - 1]
), we swap it with the element at its correct index.If
arr[i]
is out of range or already in its right position, we move to the next index.
After sorting, iterate through the
arr
again to identify the missing numbers:If the value at any index
i
does not matchi + 1
, it meansi + 1
is missing, so we add it to themissing_nums
list.Also, add the value at
arr[i]
to theextra_nums
set to help avoid duplicates when checking for missing numbers beyond the array’s length.If the length of
missing_nums
reachesk
, we stop the loop early, as we have already found the required number of missing positive numbers.
If we haven’t found
k
missing numbers from within the array, we continue searching for additional missing numbers starting fromn + 1
.Initialize
num
withn + 1
to check numbers beyond the array’s length.For each
num
, we check if it’s not in theextra_nums
set (to avoid duplicates) and add it to themissing_nums
list.Increment
num
by 1 and repeat the process until exactlyk
missing positive numbers are found.
Return the list,
missing_nums
, which contains exactlyk
missing numbers.
The slides below illustrate how we would like the algorithm to run: