Given an array of n distinct elements and we need to find the kth largest number from the given array where the value of k is larger than the size of the given array.
Example: Input: arr[] = {4, 9, 2, 7, 3, 10}, k = 3 Output: 7 Input: arr[] = {4, 9, 2, 7, 3, 10}, k = 5 Output: 3
Approach 1: Using Sorting.
//C++ code to find the kth largest element of an array #include<iostream> #include<algorithm> using namespace std; //function to return kth largest element int largestNumber(int arr[], int n, int k){ //sort the array sort(arr, arr+n); return arr[n-k]; } int main(){ int arr[] = {4, 9, 2, 7, 3, 10}; //size of given array int n = sizeof(arr)/sizeof(arr[0]); int k = 3; cout<<"The kth largest element is: "<<largestNumber(arr, n, k); return 0; }
The kth largest element is: 7
- Time Complexity: O(nlogn)
- Space Complexity: O(1)
Approach 2: Using Set data structure.
//C++ code to find kth largest element of an array using set #include<bits/stdc++.h> using namespace std; //function to return kth largest element int largestNumber(int arr[], int n, int k){ //set data structure set<int> s(arr, arr+n); //pointer to first element set<int>::iterator it = s.begin(); advance(it, n-k); return *it; } int main(){ int arr[] = {4, 9, 2, 7, 3, 10}; //size of given array int n = sizeof(arr)/sizeof(arr[0]); int k = 2; cout<<"The kth largest element is: "<<largestNumber(arr, n, k); return 0; }
The kth largest element is: 9
- Time Complexity: O(nlogn)
- Space Complexity: O(n)

Trends is an amazing magazine Blogger theme that is easy to customize and change to fit your needs.