k-th missing element in an unsorted 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 unsorted 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 unsorted array.
  • Insert all the elements into a set.
  • Find the max and min elements from the array.
  • Write a loop that iterates from min to max and maintain a variable for the count.
    • If the current element is present in the set, then increment the count.
    • If the count is equal to k, then return i.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int findMissingNumber(int arr[], int n, int k) {
   unordered_set<int> numbers;
   int count = 0;
   for (int i = 0; i < n; i++) {
      numbers.insert(arr[i]);
   }
   int max = *max_element(arr, arr + n);
   int min = *min_element(arr, arr + n);
   for (int i = min + 1; i < max; i++) {
      if (numbers.find(i) == numbers.end()) {
         count++;
      }
      if (count == k) {
         return i;
      }
   }
   return -1;
}
int main() {
   int arr[] = { 1, 10, 3, 2, 5 }, n = 5;
   int k = 3;
   cout << findMissingNumber(arr, n, k) << 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:22:37
Advertisements