You are given a strictly increasing array 'vec' and a positive integer 'k'.
Find the 'kth' positive integer missing from 'vec'.
Input: vec = [2,4,5,7] , k = 3
Output: 6
Explanation :
In the given example, first missing positive integer is 1 second missing positive integer is 3, and the third missing positive integer is 6.
Hence the answer is 6.
The first line contains an integer ‘n’ denoting the number of elements in 'vec'.
The second line contains ‘n’ space-separated integers denoting the elements of 'vec'.
The third line contains an integer ‘k’ denoting the 'kth' missing element.
Print the 'kth' positive integer missing from 'vec'.
You don't need to print anything, it has already been taken care of. Just implement the given function.
4
4 7 9 10
1
1
The missing numbers are 1, 2, 3, 5, 6, 8, 11, 12, ……, and so on.
Since 'k' is 1, the first missing element is 1.
4
4 7 9 10
4
5
Try to solve it in O(log(n)).
1 <= 'n' <= 10 ^ 4
1 <= 'k' <= 10 ^ 9
-10 ^ 9 <= 'vec[i]' <= 10 ^ 9
Time Limit : 1 sec
Use the difference between the consecutive elements.
First we remove the elements missing before the first number of the array which is trivial to check.
Then for each element check whether the current and next element is consecutive or not. If not, take the difference between the two and check till the difference is greater or equal to the given value of ‘k’. If the difference is greater, return current element - ‘count’.
Here is the algorithm :
O(n), where ‘n’ is the number of elements in the array.
We traverse the whole array once. Hence, the overall time complexity will be O(n).
O(1)
We use no extra space. Hence, the overall space complexity will be O(1).