Skip to content

1539. Kth Missing Positive Number 👍

  • Time: $O(\log n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int findKthPositive(vector<int>& arr, int k) {
    int l = 0;
    int r = arr.size();

    // Find the first index l s.t. nMissing(l) = A[l] - l - 1 >= k.
    while (l < r) {
      const int m = (l + r) / 2;
      if (arr[m] - m - 1 >= k)
        r = m;
      else
        l = m + 1;
    }

    // The k-th missing positive
    // = A[l - 1] + k - nMissing(l - 1)
    // = A[l - 1] + k - (A[l - 1] - (l - 1) - 1)
    // = A[l - 1] + k - (A[l - 1] - l)
    // = l + k
    return l + k;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int findKthPositive(int[] arr, int k) {
    int l = 0;
    int r = arr.length;

    // Find the first index l s.t. nMissing(l) = A[l] - l - 1 >= k.
    while (l < r) {
      final int m = (l + r) / 2;
      if (arr[m] - m - 1 >= k)
        r = m;
      else
        l = m + 1;
    }

    // The k-th missing positive
    // = A[l - 1] + k - nMissing(l - 1)
    // = A[l - 1] + k - (A[l - 1] - (l - 1) - 1)
    // = A[l - 1] + k - (A[l - 1] - l)
    // = l + k
    return l + k;
  }
}