K-th smallest element after removing given integers from natural numbers | Set 2
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[n-1] from it. Now the task is to find k-th smallest number in the remaining set of natural numbers.
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, … }.
Two methods are discussed in this article. This post discusses one more method.
Algorithm:
- Start traversing the array, for i ranging from 0 to N-1
- If arr[I] <= k, then increment k. Else break out of traversing the rest of the array
- The obtained k is the final answer
Note: This algorithm will only work if the input array is sorted. So first sort the given array (if not already) and in this case, the time complexity will become O(N log(N)).
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int ksmallest( int arr[], int n, int k)
{
for ( int i = 0; i < n; i++) {
if (arr[i] <= k)
k++;
else
break ;
}
return k;
}
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 int ksmallest( int arr[],
int n, int k)
{
for ( int i = 0 ; i < n; i++)
{
if (arr[i] <= k)
k++;
else
break ;
}
return 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):
for i in range (n):
if (arr[i] < = k):
k = k + 1 ;
else :
break ;
return 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)
{
for ( int i = 0; i < n; i++)
{
if (arr[i] <= k)
k++;
else
break ;
}
return 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)
{
for (let i = 0; i < n; i++)
{
if (arr[i] <= k)
k++;
else
break ;
}
return 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 )
{
for ( $i = 0; $i < $n ; $i ++)
{
if ( $arr [ $i ] <= $k )
$k ++;
else
break ;
}
return $k ;
}
$k = 1;
$arr = array (1);
$n = sizeof( $arr );
echo ksmallest( $arr , $n , $k );
?>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
16 Aug, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...