[LeetCode] Kth Missing Positive Number

1539. Kth Missing Positive Number

Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.

Return the kth positive integer that is missing from this array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
int findKthPositive(vector<int>& arr, int k) {
if(arr[0] > k) return k;
int l = 0, r = arr.size() - 1, res = INT_MAX, n = arr.size();

while(l <= r) {
int m = l + (r - l) / 2;
if(m + 1 == n) {
return arr[m] + k - (arr[m] - (m + 1));
}


int missing = arr[m] - (m + 1);
int rmissing = arr[m + 1] - (m + 2);

if(m == 0 and missing >= k) return k;

if(missing < k and k <= rmissing) {
return arr[m] + k - missing;
}
if(missing >= k) r = m - 1;
else l = m + 1;
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/06/PS/LeetCode/kth-missing-positive-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.