
- 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 an unsorted array in C++
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.
#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.
- Related Articles
- k-th missing element in sorted array in C++
- Find k closest numbers in an unsorted array in C++
- Find the K-th minimum element from an array concatenated M times in C++
- Find start and ending index of an element in an unsorted array in C++
- K’th Smallest/Largest Element in Unsorted Array in C++
- Find the Smallest Positive Number Missing From an Unsorted Array
- Missing Element in Sorted Array in C++
- Program to find out the k-th smallest difference between all element pairs in an array in C++
- K-th Element of Two Sorted Arrays in C++
- K-th Greatest Element in a Max-Heap in C++
- Find k-th smallest element in given n ranges in C++
- Finding missing element in an array of numbers in JavaScript
- Python program to find k'th smallest element in a 2D array
- Find k-th smallest element in BST (Order Statistics in BST) in C++
- Find floor and ceil in an unsorted array using C++.

Advertisements