Kth Missing Positive Number Problem


Description

LeetCode Problem 1539. 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:

1
2
3
Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.

Example 2:

1
2
3
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.


Solution

We can scan through the array. During the scanning, we use a variable i to keep track of the index of array element. We use a variable j to keep track of how many positive numbers are missing. When j reaches k, we can stop scanning. We also use a variable num to enumerate all positive numbers, starting from 1 to the largest number in the array.

During the scanning, if num is in the array, which means num = arr[i], we increase i to point to the next element in the array. If num is not in the array, we increase j which means one more positive number is missing in the array. We stop the search when j reaches k.

The time complexity is O(n), and the space complexity is O(1).


Sample C++ Code

This is a C++ implementation of the above approach.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int findKthPositive(vector<int>& arr, int k) {
    int i = 0, j = 1, num = 0;
    while (j <= k) {
        num += 1;
        if ((i < arr.size()) && (num == arr[i])) {
            i ++;
        } else {
            j ++;
        }
    }
    return num;
}

int main() {
    vector<int> arr = {2, 3, 4, 7, 11};
    int k = 5;
    cout << findKthPositive(arr, k) << endl;
}




Related Posts

Repeated DNA Sequences Problem

LeetCode 187. The DNA sequence is composed of a series...

Majority Element Problem

LeetCode 169. Given an array nums of size n, return...

Fraction To Recurring Decimal Problem

LeetCode 166. Given two integers representing the numerator and denominator...

Max Points On A Line Problem

LeetCode 149. Given an array of points where points[i] =...

Lru Cache Problem

LeetCode 146. Design a data structure that follows the constraints...

Longest Consecutive Sequence Problem

LeetCode 128. Given an unsorted array of integers nums, return...