LC 1539. Kth Missing Positive Number

Nilanjan Deb · October 11, 2020

This is my CPP solution.

class Solution {
public:
    int findKthPositive(vector<int>& arr, int k) {
        vector<int> m;
        int len = 0;
        int n = arr.size();
        if(n==0)
            return k;
        if(arr[0] != 1) {
            for(int i=1; i<arr[0]; i++) {
                m.push_back(i);
                len++;
                if(len == k )
                    return m[len-1];
            }
        }
        for(int i=0; i<n-1; i++) {
            int x = arr[i];
            while(x+1 != arr[i+1]) {
                m.push_back(++x);
                len++;
                if(len == k) {
                    return m[len-1];
                }
            }
        }
        if(len == 0){
            return arr[n-1] + k;
        }
        return arr[n-1] + (k-len);
    }
};


Dicussion Forum