k-th missing element in sorted array in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds out the k-th missing element in the given sorted array.

Find the k-th number that is missing from min to max in the given unsorted array. Let's see the steps to solve the problem.

  • Initialise the sorted array.
  • Initialise two variables difference and count with k.
  • Iterate over the array.
    • If the current element is not equal to the next element.
      • Find the difference between the two numbers.
      • If the difference is greater than or equal to k, then return current element plus count.
      • Else subtract difference from the count.
  • Return -1.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int findMissingNumber(int arr[], int k, int n) {
   int difference, count = k;
   for(int i = 0 ; i < n - 1; i++) {
      if ((arr[i] + 1) != arr[i + 1]) {
         difference = arr[i + 1] - arr[i] - 1;
         if (difference >= count) {
            return arr[i] + count;
         }else {
            count -= difference;
         }
      }
   }
   return -1;
}
int main() {
   int arr[] = { 1, 2, 3, 5, 10 }, n = 5;
   int k = 3;
   cout << findMissingNumber(arr, k, n) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

7

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 09-Apr-2021 12:27:19
Advertisements