File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
C++/Algorithms/Searching-Algorithms Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments