Intuition¶
- We leverage the
Binary Searchto find thekthmissing positive integer because the BS will help us reduce the search space efficiently. - The idea behind my solution is that we identify if a number is
kthmissing or not. Since the array is strictly increasing, the number of missing positive integers of any array elementarr[i]can be found asarr[i] - i - 1
Approach¶
1. Initialization¶
- Define
startandendpointers for the binary search
2. Early return check¶
- If
kis smaller than the first element in the array, the k-th missing number is simplyk. - If
kis greater than the total number of missing numbers up to the last element, the k-th missing number is beyond the last element. This can be calculated byk + len.
3. Binary Search¶
- Perform a binary search to find the position where the k-th missing number lies.
- Calculate the middle index
midand the count of missing numbers up tomid. - Adjust the search range based on whether the count is greater than or equal to
kor less thank.
Complexity¶
-
Time complexity:
O(logn) -
Space complexity:
O(1)
Code¶
impl Solution {
pub fn find_kth_positive(arr: Vec<i32>, k: i32) -> i32 {
let len = arr.len() as i32;
let mut start: i32 = 0;
let mut end: i32 = len - 1;
if (k < arr[0]){
return k;
}
if k > arr[arr.len() - 1] - len {
return k + len;
}
while (start < end) {
let mid = start + (end - start) / 2;
let count = arr[mid as usize] - mid - 1;
if (count >= k){
end = mid;
} else {
start = mid + 1;
}
}
start + k
}
}