forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkth-missing-positive-number.java
More file actions
45 lines (37 loc) · 898 Bytes
/
kth-missing-positive-number.java
File metadata and controls
45 lines (37 loc) · 898 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//Brute Force Linerar Time Solution
class Solution {
public int findKthPositive(int[] arr, int k) {
Set<Integer> set = new HashSet<>();
for(int el: arr){
set.add(el);
}
int count = k;
int start =1;
while(count>0){
if(set.contains(start)){
start++;
} else {
count--;
start++;
}
}
return start-1;
}
}
//Optimized Binary Search Solution
class Solution {
// TC O(logn) , SC O(1)
public int findKthPositive(int[] arr, int k) {
int low = 0;
int high = arr.length;
while(low<high){
int mid = (high -low)/2 + low;
if(arr[mid] -(mid +1) >= k){
high = mid;
} else{
low =mid+1;
}
}
return low +k;
}
}