- 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 smallest element after removing some integers from natural numbers in C++
In this tutorial, we are going to write a program that finds out the smallest element after removing some integers from the natural numbers.
We have given an array of elements and k value. Remove all the elements from natural numbers that are present in the given array. And then find the k-th smallest number from the remaining natural numbers.
Let's see the steps to solve the problem.
- Initialise the array and k.
- Initialise an array and initialise all the elements with 0 except the elements present in the given array.
- Write a loop that iterates till the size of the given array.
- Decrement the value of k if the current element is not present in the above array.
- Return the current value when k becomes zero.
- Return 0.
Example
Let's see the code.
#include <bits/stdc++.h> #define MAX 1000000 using namespace std; int smallestNumber(int arr[], int n, int k) { int flag[MAX]; memset(flag, 0, sizeof flag); for (int i = 0; i < n; i++) { flag[arr[i]] = 1; } for (int i = 1; i < MAX; i++) { if (flag[i] != 1) { k--; } if (!k) { return i; } } return 0; } int main() { int k = 2; int arr[] = { 3, 5 }; cout << smallestNumber(arr, 2, k) << endl; return 0; }
Output
If you run the above code, then you will get the following result.
2
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
Advertisements