Find Kth largest element from right of every element in the array
Last Updated :
22 Dec, 2022
Given an array arr[] of size N and an integer K. The task is to find the Kth largest element from the right of every element in the array. If there are not enough elements to the right then print the same element.
Examples:
Input: N = 6, K = 3, arr[] = {4, 5, 3, 6, 7, 2}
Output: 5 3 2 6 7 2
Explanation: The elements right to 4 are {5, 3, 6, 7, 2}.
So 3rd largest element to the right of 4 is 5.
Similarly, repeat the process for the rest of the elements.
And 7 and 2 does not have sufficient element to the right.
So, they are kept as it is.
Input: N = 5, K = 2, arr[] = {-4, 7, 5, 3, 0}
Output: 5 3 0 3 0
Naive Approach: The naive approach is to sort every subarray to the right of every element and check whether the Kth largest element exists or not. If it exists, print the Kth largest element, else print the same element.
Below is the implementation of the above approach:
C++14
#include <bits/stdc++.h>
using namespace std;
int getKLargest( int * arr, int r,
int l, int & K)
{
vector< int > v(arr, arr + l + 1);
if (l - r >= K) {
sort(v.begin() + r + 1, v.end());
return v[l - K + 1];
}
else
return v[r];
}
int main()
{
int arr[] = { -4, 7, 5, 3, 0 };
int N = sizeof (arr) / sizeof (arr[0]);
int K = 2;
for ( int i = 0; i < N; i++)
cout << getKLargest(arr, i, N - 1, K)
<< " " ;
return 0;
}
|
Java
import java.util.*;
class GFG{
static void sort( int [] arr, int N, int a, int b)
{
int l = Math.min(a, b);
int r = Math.max(a, b);
int [] temp = new int [r - l + 1 ];
int j = 0 ;
for ( int i = l; i <= r; i++) {
temp[j] = arr[i];
j++;
}
Arrays.sort(temp);
j = 0 ;
for ( int i = l; i <= r; i++) {
arr[i] = temp[j];
j++;
}
}
static int getKLargest( int [] arr, int r, int l, int K)
{
int n = arr.length;
int [] v = new int [l + 1 ];
for ( int i = 0 ; i < l + 1 ; i++) {
v[i] = arr[i];
}
if (l - r >= K) {
sort(v, n, r + 1 , n - 1 );
return v[l - K + 1 ];
}
else
return v[r];
}
public static void main(String[] args)
{
int arr[] = { - 4 , 7 , 5 , 3 , 0 };
int N = arr.length;
int K = 2 ;
for ( int i = 0 ; i < N; i++)
System.out.print(getKLargest(arr, i, N - 1 , K)
+ " " );
}
}
|
Python3
def getKLargest(arr, r, l, K):
v = arr[ 0 : l + 1 ]
if (l - r > = K):
temp1 = v[ 0 : r + 1 ]
temp = v[r + 1 :]
temp.sort()
v = temp1 + temp
return v[l - K + 1 ]
else :
return v[r]
arr = [ - 4 , 7 , 5 , 3 , 0 ]
N = len (arr)
K = 2
for i in range (N):
print (getKLargest(arr, i, N - 1 , K), end = " " )
|
C#
using System;
class GFG
{
static void sort( int [] arr, int N, int a, int b)
{
int l = Math.Min(a, b);
int r = Math.Max(a, b);
int [] temp = new int [r - l + 1];
int j = 0;
for ( int i = l; i <= r; i++) {
temp[j] = arr[i];
j++;
}
Array.Sort(temp);
j = 0;
for ( int i = l; i <= r; i++) {
arr[i] = temp[j];
j++;
}
}
static int getKLargest( int [] arr, int r, int l, int K)
{
int n = arr.Length;
int [] v = new int [l + 1];
for ( int i = 0; i < l + 1; i++) {
v[i] = arr[i];
}
if (l - r >= K) {
sort(v, n, r + 1, n - 1);
return v[l - K + 1];
}
else
return v[r];
}
public static void Main()
{
int [] arr = { -4, 7, 5, 3, 0 };
int N = arr.Length;
int K = 2;
for ( int i = 0; i < N; i++)
Console.Write(getKLargest(arr, i, N - 1, K)
+ " " );
}
}
|
Javascript
<script>
function getKLargest(arr, r,
l, K)
{
let v = arr.slice(0, l + 1);
if (l - r >= K) {
let temp1 = v.slice(0, r + 1);
let temp = v.slice(r + 1);
temp.sort( function (a, b) { return a - b })
v = temp1.concat(temp)
return v[l - K + 1];
}
else
return v[r];
}
let arr = [-4, 7, 5, 3, 0];
let N = arr.length;
let K = 2;
for (let i = 0; i < N; i++)
document.write(getKLargest(arr, i, N - 1, K) + " " )
</script>
|
Time Complexity: O(N2 * logN)
Auxiliary Space: O(N)
Approach based on Sets: Another approach is to use sets. Though both the approaches have same the time complexity, sets have an inbuilt sorting feature, it doesn’t require explicit sorting.
Below is the implementation of the above approach.
C++14
#include <bits/stdc++.h>
using namespace std;
int getKLargest(vector< int >& arr, int r,
int l, int & k)
{
set< int > s(arr.begin() + r + 1,
arr.end());
if (l - r >= k) {
set< int >::iterator it = s.end();
advance(it, -k);
return *it;
}
else
return arr[r];
}
int main()
{
int arr[] = { -4, 7, 5, 3, 0 };
int N = sizeof (arr) / sizeof (arr[0]);
int i, K = 2;
vector< int > a(arr, arr + N);
for (i = 0; i < N; i++)
cout << getKLargest(a, i, N - 1, K)
<< " " ;
return 0;
}
|
Java
import java.util.*;
class GFG{
static int getKLargest(List<Integer> arr, int r,
int l, int k)
{
HashSet<Integer> s = new HashSet<>(arr.subList(r+ 1 ,arr.size()));
List<Integer> a = new ArrayList<>(s);
if (l - r >= k) {
return a.get(a.size()-k);
}
else
return arr.get(r);
}
public static void main(String[] args)
{
Integer arr[] = { - 4 , 7 , 5 , 3 , 0 };
int N = arr.length;
int i= 0 ;
int K = 2 ;
List<Integer> a = Arrays.asList(arr);
for (i = 0 ; i < N; i++)
System.out.print(getKLargest(a, i, N - 1 , K)
+ " " );
}
}
|
Python3
def getKLargest( arr , r , l , k):
s = set ()
for i in range (r + 1 , len (arr)):
s.add(arr[i])
a = []
for p in s:
a.append(p)
if (l - r > = k):
return a[ len (a) - k]
else :
return arr[r]
arr = [ - 4 , 7 , 5 , 3 , 0 ]
N = len (arr)
i = 0
K = 2
a = arr
for i in range (N):
print (getKLargest(a, i, N - 1 , K) ,end = " " )
|
C#
using System;
using System.Collections.Generic;
public class GFG{
static int getKLargest(List< int > arr, int r,
int l, int k)
{
HashSet< int > s = new HashSet< int >(arr.GetRange(r+1,arr.Count-(r+1)));
List< int > a = new List< int >(s);
a.Reverse();
if (l - r >= k) {
return a[a.Count-k];
}
else
return arr[r];
}
public static void Main(String[] args)
{
int []arr = { -4, 7, 5, 3, 0 };
int N = arr.Length;
int i=0;
int K = 2;
List< int > a = new List< int >(arr);
for (i = 0; i < N; i++)
Console.Write(getKLargest(a, i, N - 1, K)
+ " " );
}
}
|
Javascript
<script>
function getKLargest( arr , r , l , k) {
var s = new Set();
for (let i = r+1;i<arr.length;i++)
s.add(arr[i]);
var a = [];
for (let p of s)
a.push(p);
a.reverse();
if (l - r >= k) {
return a[a.length - k];
} else
return arr[r];
}
var arr = [ -4, 7, 5, 3, 0 ];
var N = arr.length;
var i = 0;
var K = 2;
var a = (arr);
for ( var i = 0; i < N; i++)
document.write(getKLargest(a, i, N - 1, K) + " " );
</script>
|
Time Complexity: O(N2 * logN)
Auxiliary Space: O(N)
Efficient Approach: The idea to efficiently solve the problem is:
Insert each element of the array in a vector and sort them in decreasing order. Then delete each element and print the Kth largest from the sorted vector.
Follow the steps mentioned below to implement the idea:
- First, insert all the elements in a vector.
- Sort the vector in decreasing order.
- Iterate through the array from i = 0 to N:
- Delete arr[i] from the vector.
- If there are at least K elements left, print the Kth largest from the vector.
- Otherwise, print the same element.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int getKLargest( int arr[], int n, int k)
{
vector< int > v(arr, arr + n );
sort(v.begin(),v.end(),greater< int >());
for ( int i=0;i<n;i++)
{
v.erase( remove (v.begin(), v.end(), arr[i]), v.end());
if (v.size()>=k)
{
cout<<v[k-1]<< " " ;
}
else
{
cout<<arr[i]<< " " ;
}
}
}
int main()
{
int arr[] = { -4, 7, 5, 3, 0 };
int N = sizeof (arr) / sizeof (arr[0]);
int K = 2;
getKLargest(arr, N , K);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void getKLargest( int arr[],
int n, int k)
{
Vector<Integer> v
= new Vector<Integer>();
for ( int i = 0 ; i < n; i++)
v.add(arr[i]);
Collections.sort(v, Collections.reverseOrder());
for ( int i = 0 ; i < n; i++)
{
v.remove( new Integer(arr[i]));
if (v.size() >= k)
System.out.print(v.get(k - 1 ) + " " );
else
System.out.print(arr[i] + " " );
}
}
public static void main(String args[])
{
int arr[] = { - 4 , 7 , 5 , 3 , 0 };
int N = arr.length;
int K = 2 ;
getKLargest(arr, N , K);
}
}
|
Python3
def getKLargest(arr, n, k):
v = []
for i in arr:
v.append(i)
v.sort()
v.reverse()
for i in range (n):
v.remove(arr[i])
if ( len (v) > = k):
print (v[k - 1 ], end = ' ' )
else :
print (arr[i], end = ' ' )
if __name__ = = '__main__' :
arr = [ - 4 , 7 , 5 , 3 , 0 ]
N = len (arr)
K = 2
getKLargest(arr, N , K)
|
C#
using System;
using System.Linq;
public class GFG {
public static void getKLargest( int [] arr, int n, int k)
{
var v = arr.ToList();
v.Sort((a, b) = > b - a);
for ( int i = 0; i < n; i++) {
v.Remove(arr[i]);
if (v.Count >= k) {
Console.Write(v[k - 1] + " " );
}
else {
Console.Write(arr[i] + " " );
}
}
}
public static void Main()
{
int [] arr = { -4, 7, 5, 3, 0 };
int N = arr.Length;
int K = 2;
getKLargest(arr, N, K);
}
}
|
Javascript
<script>
function getKLargest(arr, n, k)
{
let v = arr.slice();
v.sort((a,b)=>b-a);
for (let i=0;i<n;i++)
{
v.splice(v.indexOf(arr[i]),1);
if (v.length>=k)
{
document.write(v[k-1], " " );
}
else
{
document.write(arr[i], " " );
}
}
}
let arr = [ -4, 7, 5, 3, 0 ];
let N = arr.length;
let K = 2;
getKLargest(arr, N , K);
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...