
- 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 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.
- Related Articles
- Find k-th smallest element in given n ranges in C++
- Find the k-th smallest divisor of a natural number N in C++
- C++ code to find xth element after removing numbers
- Find k-th smallest element in BST (Order Statistics in BST) in C++
- K-th Smallest Prime Fraction in C++
- Python program to find k'th smallest element in a 2D array
- Find the k smallest numbers after deleting given elements in C++
- Smallest number after removing n digits in JavaScript
- K-th Smallest in Lexicographical Order in C++
- Find K-th Smallest Pair Distance in C++
- Median after K additional integers in C++
- Compare natural numbers and positive integers.
- C++ Program to get number at position k after positioning n natural numbers
- Find m-th smallest value in k sorted arrays in C++
- Program to find out the k-th smallest difference between all element pairs in an array in C++

Advertisements