C++ Program for k-th missing element in sorted array
Last Updated :
05 May, 2023
Given an increasing sequence a[], we need to find the K-th missing contiguous element in the increasing sequence which is not present in the sequence. If no k-th missing element is there output -1.
Examples :
Input : a[] = {2, 3, 5, 9, 10};
k = 1;
Output : 1
Explanation: Missing Element in the increasing
sequence are {1,4, 6, 7, 8}. So k-th missing element
is 1
Input : a[] = {2, 3, 5, 9, 10, 11, 12};
k = 4;
Output : 7
Explanation: missing element in the increasing
sequence are {1, 4, 6, 7, 8} so k-th missing
element is 7
Approach 1: Start iterating over the array elements, and for every element check if the next element is consecutive or not, if not, then take the difference between these two, and check if the difference is greater than or equal to given k, then calculate ans = a[i] + count, else iterate for next element.
C++
#include <bits/stdc++.h>
using namespace std;
int missingK( int a[], int k,
int n)
{
int difference = 0,
ans = 0, count = k;
bool flag = 0;
for ( int i = 0 ; i < n - 1; i++)
{
difference = 0;
if ((a[i] + 1) != a[i + 1])
{
difference +=
(a[i + 1] - a[i]) - 1;
if (difference >= count)
{
ans = a[i] + count;
flag = 1;
break ;
}
else
count -= difference;
}
}
if (flag)
return ans;
else
return -1;
}
int main()
{
int a[] = {1, 5, 11, 19};
int k = 11;
int n = sizeof (a) / sizeof (a[0]);
int missing = missingK(a, k, n);
cout << missing << endl;
return 0;
}
|
Time Complexity: O(n), where n is the number of elements in the array.
Auxiliary Space: O(1) as no extra space has been used.
Approach 2:
Apply a binary search. Since the array is sorted we can find at any given index how many numbers are missing as arr[index] – (index+1). We would leverage this knowledge and apply binary search to narrow down our hunt to find that index from which getting the missing number is easier.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int missingK(vector< int >& arr, int k)
{
int n = arr.size();
int l = 0, u = n - 1, mid;
while (l <= u)
{
mid = (l + u)/2;
int numbers_less_than_mid = arr[mid] -
(mid + 1);
if (numbers_less_than_mid == k)
{
if (mid > 0 && (arr[mid - 1] - (mid)) == k)
{
u = mid - 1;
continue ;
}
return arr[mid]-1;
}
if (numbers_less_than_mid < k)
{
l = mid + 1;
}
else if (k < numbers_less_than_mid)
{
u = mid - 1;
}
}
if (u < 0)
return k;
int less = arr[u] - (u + 1);
k -= less;
return arr[u] + k;
}
int main()
{
vector< int > arr = {2,3,4,7,11};
int k = 5;
cout << "Missing kth number = " <<
missingK(arr, k)<<endl;
return 0;
}
|
Time Complexity: O(log(n)), where n is the number of elements in the array.
Auxiliary Space: O(1) as no extra space has been taken.
Please refer complete article on k-th missing element in sorted array for more details!
Share your thoughts in the comments
Please Login to comment...