Leetcode 1539. Kth Missing Positive Number
Given an array arr
of positive integers sorted in a strictly increasing order, and an integer k
, find the kth
positive integer that is missing from this array.
Example 1:
Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,...]. The 5th missing positive integer is 9.
Example 2:
Input: arr = [1,2,3,4], k = 2
Output: 6
Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.
arr
?arr
? (e.g., if they can have duplicates, etc.)k
?missing_count
, to keep track of the number of missing integers.index
, to traverse the array.missing_count
.missing_count
equals k
.k
th missing positive integer.n
is the length of the array. This is because in the worst case, we might need to iterate through all numbers till we find the k
th missing number, checking each against the array.public class Solution {
public int findKthPositive(int[] arr, int k) {
int missing_count = 0;
int current_number = 1;
int index = 0;
while (missing_count < k) {
// Check if current_number is missing in the array
if (index < arr.length && arr[index] == current_number) {
index++;
} else {
missing_count++;
}
// Check if the current number is the kth missing number
if (missing_count == k) {
return current_number;
}
current_number++;
}
// As a safety return, although theoretically we should never reach here
return -1;
}
}
This code takes into account the given array and checks every integer starting from 1 to find the kth
missing positive integer efficiently. If the logic proceeds logically, it ensures that k
missing elements are calculated and returned.
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?