Given an array arr
of positive integers sorted in a strictly increasing order, and an integer k
, return the k
-th missing positive number starting from the left.
arr
?arr
?k
?k
is impossibly large?arr = [2, 3, 4, 7, 11]
, k = 5
9
(Missing numbers sequence: [1, 5, 6, 8, 9, 10, …])missing_count
to track the number of missing numbers.1
and compare with elements in arr
.k
-th missing number.arr
.O(n + k)
, where n
is the length of the array and k
is the k
-th missing number being checked.def findKthPositive(arr, k):
missing_count = 0
current = 1
index = 0
n = len(arr)
while missing_count < k:
if index < n and arr[index] == current:
index += 1
else:
missing_count += 1
if missing_count < k:
current += 1
return current
# Test the function
print(findKthPositive([2, 3, 4, 7, 11], 5)) # Output: 9
print(findKthPositive([1, 2, 3, 4], 2)) # Output: 6
missing_count
to count the missing numbers.current
to evaluate each natural number sequentially.index
to track the position within arr
.k
-th missing number is found:
current
is present in arr
, move to the next element in arr
.current
is missing in arr
, increment the missing_count
.current
after updating either missing_count
or index
.missing_count
equals k
, the last value of current
will be the k-th missing number.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?