
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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.
- Related Articles
- k-th missing element in an unsorted array in C++
- Missing Element in Sorted Array in C++
- K-th Element of Two Sorted Arrays in C++
- Find missing element in a sorted array of consecutive numbers in Python
- Find missing element in a sorted array of consecutive numbers in C++
- Find m-th smallest value in k sorted arrays in C++
- Python program to find k'th smallest element in a 2D array
- Find the K-th minimum element from an array concatenated M times in C++
- K-th Greatest Element in a Max-Heap in C++
- Find k-th smallest element in given n ranges in C++
- Find the only missing number in a sorted array using C++
- Single Element in a Sorted Array in C++
- Program to find out the k-th smallest difference between all element pairs in an array in C++
- Finding first unique element in sorted array in JavaScript
- Find k-th smallest element in BST (Order Statistics in BST) in C++

Advertisements