Given an array arr[] of size ‘n’ and a positive integer k. Consider series of natural numbers and remove arr[0], arr[1], arr[2], …, arr[p] from it. Now the task is to find k-th smallest number in the remaining set of natural numbers. If no such number exists print “-1”.
Examples :
Input : arr[] = { 1 } and k = 1.
Output: 2
Natural numbers are {1, 2, 3, 4, .... }
After removing {1}, we get {2, 3, 4, ...}.
Now, K-th smallest element = 2.
Input : arr[] = {1, 3}, k = 4.
Output : 6
First 5 Natural number {1, 2, 3, 4, 5, 6, .. }
After removing {1, 3}, we get {2, 4, 5, 6, ... }.
Method 1 (Simple):
Make an auxiliary array b[] for presence/absence of natural numbers and initialize all with 0. Make all the integer equal to 1 which are present in array arr[] i.e b[arr[i]] = 1. Now, run a loop and decrement k whenever unmarked cell is encountered. When the value of k is 0, we get the answer.
Steps to solve the problem:
1. declare an array b of size max.
2. mark complete array as unmarked by 0.
3. iterate through i=0 till n:
* update b[arr[i]] to 1.
4. iterate through j=0 till max:
* check if b[j] is not equal to 1 then decrement k.
* check if k is not equal to 0 then return j.
Below is implementation of this approach:
C++
#include <bits/stdc++.h>
#define MAX 1000000
using namespace std;
int ksmallest( int arr[], int n, int k)
{
int b[MAX];
memset (b, 0, sizeof b);
for ( int i = 0; i < n; i++)
b[arr[i]] = 1;
for ( int j = 1; j < MAX; j++) {
if (b[j] != 1)
k--;
if (!k)
return j;
}
}
int main()
{
int k = 1;
int arr[] = { 1 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << ksmallest(arr, n, k);
return 0;
}
|
Java
class GFG {
static final int MAX = 1000000 ;
static int ksmallest( int arr[], int n, int k)
{
int b[] = new int [MAX];
for ( int i = 0 ; i < n; i++) {
b[arr[i]] = 1 ;
}
for ( int j = 1 ; j < MAX; j++) {
if (b[j] != 1 ) {
k--;
}
if (k != 1 ) {
return j;
}
}
return Integer.MAX_VALUE;
}
public static void main(String[] args)
{
int k = 1 ;
int arr[] = { 1 };
int n = arr.length;
System.out.println(ksmallest(arr, n, k));
}
}
|
Python3
MAX = 1000000
def ksmallest(arr, n, k):
b = [ 0 ] * MAX ;
for i in range (n):
b[arr[i]] = 1 ;
for j in range ( 1 , MAX ):
if (b[j] ! = 1 ):
k - = 1 ;
if (k is not 1 ):
return j;
k = 1 ;
arr = [ 1 ];
n = len (arr);
print (ksmallest(arr, n, k));
|
C#
using System;
class GFG {
static int MAX = 1000000;
static int ksmallest( int [] arr, int n, int k)
{
int [] b = new int [MAX];
for ( int i = 0; i < n; i++) {
b[arr[i]] = 1;
}
for ( int j = 1; j < MAX; j++) {
if (b[j] != 1) {
k--;
}
if (k != 1) {
return j;
}
}
return int .MaxValue;
}
public static void Main()
{
int k = 1;
int [] arr = { 1 };
int n = arr.Length;
Console.WriteLine(ksmallest(arr, n, k));
}
}
|
Javascript
<script>
let MAX = 1000000;
function ksmallest(arr, n, k)
{
let b = [];
for (let i = 0; i < n; i++)
{
b[arr[i]] = 1;
}
for (let j = 1; j < MAX; j++)
{
if (b[j] != 1)
{
k--;
}
if (k != 1)
{
return j;
}
}
return Number.MAX_VALUE;
}
let k = 1;
let arr = [1];
let n = arr.length;
document.write(ksmallest(arr, n, k));
</script>
|
PHP
<?php
$MAX = 10000;
function ksmallest( $arr , $n , $k )
{
global $MAX ;
$b = array_fill (0, $MAX , 0);
for ( $i = 0; $i < $n ; $i ++)
$b [ $arr [ $i ]] = 1;
for ( $j = 1; $j < $MAX ; $j ++)
{
if ( $b [ $j ] != 1)
$k --;
if ( $k == 0)
return $j ;
}
}
$k = 1;
$arr = array ( 1 );
$n = count ( $arr );
echo ksmallest( $arr , $n , $k );
?>
|
Time Complexity: O(MAX)
Auxiliary Space: O(MAX)
Method 2 (Efficient):
First, sort the array arr[]. Observe, there will be arr[0] – 1 numbers between 0 and arr[0], similarly, arr[1] – arr[0] – 1 numbers between arr[0] and arr[1] and so on. So, if k lies between arr[i] – arr[i+1] – 1, then return K-th smallest element in the range. Else reduce k by arr[i] – arr[i+1] – 1 i.e., k = k – (arr[i] – arr[i+1] – 1).
Algorithm to solve the problem:
1. Sort the array arr[].
2. For i = 1 to n. Find c = arr[i+1] - arr[i] -1.
a) if k - c <= 0, return arr[i-1] + k.
b) else k = k - c.
Below is implementation of this approach:
C++
#include <bits/stdc++.h>
using namespace std;
int ksmallest( int arr[], int n, int k)
{
sort(arr, arr + n);
if (k < arr[0])
return k;
if (k == arr[0])
return arr[0] + 1;
if (k > arr[n - 1])
return k + n;
if (arr[0] == 1)
k--;
else
k -= (arr[0] - 1);
for ( int i = 1; i < n; i++) {
int c = arr[i] - arr[i - 1] - 1;
if (k <= c)
return arr[i - 1] + k;
else
k -= c;
}
return arr[n - 1] + k;
}
int main()
{
int k = 1;
int arr[] = { 1 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << ksmallest(arr, n, k);
return 0;
}
|
Java
import java.util.Arrays;
import java.io.*;
class GFG {
static int ksmallest( int arr[],
int n, int k)
{
Arrays.sort(arr);
if (k < arr[ 0 ])
return k;
if (k == arr[ 0 ])
return arr[ 0 ] + 1 ;
if (k > arr[n - 1 ])
return k + n;
if (arr[ 0 ] == 1 )
k--;
else
k -= (arr[ 0 ] - 1 );
for ( int i = 1 ; i < n; i++) {
int c = arr[i] - arr[i - 1 ] - 1 ;
if (k <= c)
return arr[i - 1 ] + k;
else
k -= c;
}
return arr[n - 1 ] + k;
}
public static void main(String[] args)
{
int k = 1 ;
int arr[] = { 1 };
int n = arr.length;
System.out.println(ksmallest(arr, n, k));
}
}
|
Python3
def ksmallest(arr, n, k):
arr.sort();
if (k < arr[ 0 ]):
return k;
if (k = = arr[ 0 ]):
return arr[ 0 ] + 1 ;
if (k > arr[n - 1 ]):
return k + n;
if (arr[ 0 ] = = 1 ):
k - = 1 ;
else :
k - = (arr[ 0 ] - 1 );
for i in range ( 1 , n):
c = arr[i] - arr[i - 1 ] - 1 ;
if (k < = c):
return arr[i - 1 ] + k;
else :
k - = c;
return arr[n - 1 ] + k;
k = 1 ;
arr = [ 1 ];
n = len (arr);
print (ksmallest(arr, n, k));
|
C#
using System;
class GFG {
static int ksmallest( int [] arr,
int n, int k)
{
Array.Sort(arr);
if (k < arr[0])
return k;
if (k == arr[0])
return arr[0] + 1;
if (k > arr[n - 1])
return k + n;
if (arr[0] == 1)
k--;
else
k -= (arr[0] - 1);
for ( int i = 1; i < n; i++) {
int c = arr[i] - arr[i - 1] - 1;
if (k <= c)
return arr[i - 1] + k;
else
k -= c;
}
return arr[n - 1] + k;
}
static public void Main()
{
int k = 1;
int [] arr = { 1 };
int n = arr.Length;
Console.WriteLine(ksmallest(arr, n, k));
}
}
|
Javascript
<script>
function ksmallest(arr, n, k)
{
arr.sort( function (a, b){ return a - b});
if (k < arr[0])
return k;
if (k == arr[0])
return arr[0] + 1;
if (k > arr[n - 1])
return k + n;
if (arr[0] == 1)
k--;
else
k -= (arr[0] - 1);
for (let i = 1; i < n; i++)
{
let c = arr[i] - arr[i - 1] - 1;
if (k <= c)
return arr[i - 1] + k;
else
k -= c;
}
return arr[n - 1] + k;
}
let k = 1;
let arr = [1];
let n = arr.length;
document.write(ksmallest(arr, n, k));
</script>
|
PHP
<?php
function ksmallest( $arr , $n , $k )
{
sort( $arr );
if ( $k < $arr [0])
return $k ;
if ( $k == $arr [0])
return $arr [0] + 1;
if ( $k > $arr [ $n - 1])
return $k + $n ;
if ( $arr [0] == 1)
$k --;
else
$k -= ( $arr [0] - 1);
for ( $i = 1; $i < $n ; $i ++)
{
$c = $arr [ $i ] - $arr [ $i - 1] - 1;
if ( $k <= $c )
return $arr [ $i - 1] + $k ;
else
$k -= $c ;
}
return $arr [ $n - 1] + $k ;
}
$k = 1;
$arr = array ( 1 );
$n = sizeof( $arr );
echo ksmallest( $arr , $n , $k );
?>
|
Time Complexity: O(nlog(n))
Auxiliary Space: O(1)
Set Approach:
- Create a set to store the elements of the array.
- Iterate through the array and add each element to the set.
- Start changing num to 1, which represents the current generation number.
If k is greater than 0:
If the set contains num, continue by incrementing num.
If num is not available, reduce k by 1 .
Increase num by1.
- Returns the value of num as the k-th smallest number.
C++
#include <iostream>
#include <unordered_set>
using namespace std;
int findKthSmallestNumber( int arr[], int n, int k) {
unordered_set< int > set;
for ( int i = 0; i < n; i++) {
set.insert(arr[i]);
}
int num = 1;
while (k > 0) {
if (set.count(num)) {
num++;
} else {
k--;
num++;
}
}
return num - 1;
}
int main() {
int arr[] = {1, 3};
int n = sizeof (arr) / sizeof (arr[0]);
int k = 4;
int kthSmallest = findKthSmallestNumber(arr, n, k);
cout << "K-th smallest number: " << kthSmallest << endl;
return 0;
}
|
Java
import java.util.HashSet;
import java.util.Set;
public class KthSmallestNumber {
public static void main(String[] args) {
int [] arr = { 1 , 3 };
int k = 4 ;
int kthSmallest = findKthSmallestNumber(arr, k);
System.out.println( "K-th smallest number: " + kthSmallest);
}
public static int findKthSmallestNumber( int [] arr, int k) {
Set<Integer> set = new HashSet<>();
for ( int num : arr) {
set.add(num);
}
int num = 1 ;
while (k > 0 ) {
if (set.contains(num)) {
num++;
} else {
k--;
num++;
}
}
return num - 1 ;
}
}
|
Python3
def find_kth_smallest_number(arr, k):
unique_nums = set (arr)
num = 1
while k > 0 :
if num in unique_nums:
num + = 1
else :
k - = 1
num + = 1
return num - 1
if __name__ = = "__main__" :
arr = [ 1 , 3 ]
k = 4
kth_smallest = find_kth_smallest_number(arr, k)
print ( "K-th smallest number:" , kth_smallest)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int FindKthSmallestNumber( int [] arr, int n,
int k)
{
HashSet< int > set = new HashSet< int >();
for ( int i = 0; i < n; i++) {
set .Add(arr[i]);
}
int num = 1;
while (k > 0) {
if ( set .Contains(num)) {
num++;
}
else {
k--;
num++;
}
}
return num - 1;
}
static void Main()
{
int [] arr = { 1, 3 };
int n = arr.Length;
int k = 4;
int kthSmallest = FindKthSmallestNumber(arr, n, k);
Console.WriteLine( "K-th smallest number: "
+ kthSmallest);
}
}
|
Javascript
function findKthSmallestNumber(arr, k) {
const set = new Set();
for (let i = 0; i < arr.length; i++) {
set.add(arr[i]);
}
let num = 1;
while (k > 0) {
if (set.has(num)) {
num++;
} else {
k--;
num++;
}
}
return num - 1;
}
const arr = [1, 3];
const k = 4;
const kthSmallest = findKthSmallestNumber(arr, k);
console.log( "K-th smallest number:" , kthSmallest);
|
Output
K-th smallest number: 6
Time Complexity: It takes O(n) time to build a set by iterating through an array, where n is the size of the array.
Iterating through the natural numbers until the kth smallest number is reached takes O(k) time in the worst case.
Thus, the total time complexity is O(n + k).
Space Complexity: O(n), where n is the size of the array, as it can potentially store all the distinct elements of the array.
Counting Approach:
- Create an array of size max+2, where max is the maximum number of elements in the given array.
- Initialize all elements of the count array to 0 .
- Increase the number of each element in the count array by iterating through the given array.
- Start changing num to 1, which represents the current generation number.
If k is greater than 0:
If the number of nums in the count array is greater than 0, decrement the count by 1 and continue.
If the count is 0, decrease k by 1 .
Increase num by
- Returns the num value as the k-th smallest number
C++
#include <iostream>
#include <algorithm>
using namespace std;
int findKthSmallestNumber( int arr[], int n, int k) {
int max_num = *max_element(arr, arr + n);
int * count = new int [max_num + 2]();
for ( int i = 0; i < n; i++) {
count[arr[i]]++;
}
int num = 1;
while (k > 0) {
if (count[num] > 0) {
count[num]--;
} else {
k--;
}
num++;
}
delete [] count;
return num - 1;
}
int main() {
int arr[] = {1, 3};
int n = sizeof (arr) / sizeof (arr[0]);
int k = 4;
int kthSmallest = findKthSmallestNumber(arr, n, k);
cout << "K-th smallest number: " << kthSmallest << endl;
return 0;
}
|
Java
public class KthSmallestNumber {
public static void main(String[] args) {
int [] arr = { 1 , 3 };
int k = 4 ;
int kthSmallest = findKthSmallestNumber(arr, k);
System.out.println( "K-th smallest number: " + kthSmallest);
}
public static int findKthSmallestNumber( int [] arr, int k) {
int max = Integer.MIN_VALUE;
for ( int num : arr) {
max = Math.max(max, num);
}
int [] count = new int [max + 1 ];
for ( int num : arr) {
count[num]++;
}
int num = 1 ;
while (k > 0 ) {
if (num < count.length && count[num] > 0 ) {
count[num]--;
} else {
k--;
}
num++;
}
return num - 1 ;
}
}
|
Python3
def find_kth_smallest_number(arr, k):
max_num = max (arr)
count = [ 0 ] * (max_num + 1 )
for num in arr:
count[num] + = 1
num = 1
while k > 0 :
if num < len (count) and count[num] > 0 :
count[num] - = 1
else :
k - = 1
num + = 1
return num - 1
def main():
arr = [ 1 , 3 ]
k = 4
kth_smallest = find_kth_smallest_number(arr, k)
print ( "K-th smallest number:" , kth_smallest)
if __name__ = = "__main__" :
main()
|
C#
using System;
public class KthSmallestNumber {
public static void Main( string [] args)
{
int [] arr = { 1, 3 };
int k = 4;
int kthSmallest = FindKthSmallestNumber(arr, k);
Console.WriteLine( "K-th smallest number: "
+ kthSmallest);
}
public static int FindKthSmallestNumber( int [] arr,
int k)
{
int max = int .MinValue;
foreach ( int numValue in
arr)
{
max = Math.Max(max, numValue);
}
int [] count
= new int [max
+ 1];
foreach ( int numValue in
arr)
{
count[numValue]++;
}
int currentNum = 1;
while (k > 0) {
if (currentNum < count.Length
&& count[currentNum]
> 0)
{
count[currentNum]--;
}
else {
k--;
}
currentNum++;
}
return currentNum - 1;
}
}
|
Javascript
function findKthSmallestNumber(arr, k) {
let max = Number.MIN_VALUE;
for (let numValue of arr) {
max = Math.max(max, numValue);
}
const count = new Array(max + 1).fill(0);
for (let numValue of arr) {
count[numValue]++;
}
let currentNum = 1;
while (k > 0) {
if (currentNum < count.length && count[currentNum] > 0) {
count[currentNum]--;
} else {
k--;
}
currentNum++;
}
return currentNum - 1;
}
const arr = [1, 3];
const k = 4;
const kthSmallest = findKthSmallestNumber(arr, k);
console.log( "K-th smallest number: " + kthSmallest);
|
Output
K-th smallest number: 6
Time Complexity: It takes O(n) time to find the largest element in the array, where n is the size of the array.
When you start an accounting system, it takes O(n) time to count every occurrence in the system.
Iterating through the natural numbers until the kth smallest number is reached takes O(k) time in the worst case.
Thus, the total time complexity is O(n + k).
Space Complexity: O(n), where n is the size of the array.
More efficient method : K-th smallest element after removing given integers from natural numbers | Set 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!