Skip to content

Commit 8f69836

Browse files
committed
Added cpp file of finding Kth Positive Integer
1 parent 142d7cd commit 8f69836

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/* Problem Statement
2+
Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.
3+
Find the kth positive integer that is missing from this array
4+
Constraints:
5+
1 <= arr.length <= 1000
6+
1 <= arr[i] <= 1000
7+
1 <= k <= 1000
8+
arr[i] < arr[j] for 1 <= i < j <= arr.length
9+
*/
10+
#include<bits/stdc++.h>
11+
using namespace std;
12+
int findKthPositive(vector<int>& arr, int k)
13+
{
14+
int b[10001];
15+
int i; int ans = 0;
16+
for (i = 0; i <= 10000; i++)
17+
b[i] = i; //stores value i at every index i
18+
for (i = 0; i < arr.size(); i++)
19+
b[arr[i]] = -1; //stores -1 for elements already in the array
20+
21+
for (i = 1; i <= 10000; i++)
22+
{
23+
if (b[i] != -1) //if it is not -1, then it is counted towards kth integer, so k--
24+
k--;
25+
if (k == 0) // if k becomes 0, it means we have found kth positive integer
26+
{
27+
ans = i; //value is stored in ans
28+
break;
29+
}
30+
}
31+
return ans;
32+
}
33+
int main()
34+
{
35+
vector<int> arr;
36+
int n, k, i;
37+
cin >> n >> k;
38+
for (i = 0; i < n; i++) //takes input from user
39+
{
40+
int a;
41+
cin >> a;
42+
arr.push_back(a);
43+
}
44+
cout << findKthPositive(arr, k);
45+
return 0;
46+
}

0 commit comments

Comments
 (0)