- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
k-th missing element in sorted array in C++
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.
- If the current element is not equal to the next element.
- Return -1.
Example
Let's see the code.
#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.
Advertisements
To Continue Learning Please Login
Login with Google