Just add k out-of-range numbers to the array! This way, the first k missing positive numbers will for sure be within the range of the array and we won’t need the trick with the extra numbers.
Time and space complexities are the same.
Here’s the code:
def find_first_k_missing_positive(nums, k):
nums += [-1]*k
i = 0
while i < len(nums):
j = nums[i]-1
if j >= 0 and j < len(nums) and nums[i] != nums[j]:
nums[i], nums[j] = nums[j], nums[i]
else:
i += 1
missingNumbers = []
for i in range(len(nums)):
if i != nums[i]-1:
missingNumbers.append(i+1)
if len(missingNumbers) == k:
break
return missingNumbers