At Least Two Greater Elements Problem (Geeks for Geeks)
This tutorial contains a complete walk-through of the At Least Two Greater Elements problem from the Geeks for Geeks website. It features the implementation of the solution code in two programming languages: Python and C++.
Problem Descriptionβ
Given an array of N distinct elements, the task is to find all elements in array except two greatest elements in sorted order.
Examplesβ
Example 1:
Input : a[] = {2, 8, 7, 1, 5}
Output : 1 2 5
Explanation : The output three elements have two or more greater elements.
Example 2:
Input : a[] = {7, -2, 3, 4, 9, -1}
Output : -2 -1 3 4
Your Taskβ
You don't need to read input or print anything. Your task is to complete the function findElements()
which takes the array A[]
and its size N as inputs and return the vector sorted values denoting the elements in array which have at-least two greater elements than themselves.
Expected Time Complexity: Expected Auxiliary Space:
Constraintsβ
3 β€ N β€ 10^5
-10^6 β€ Ai β€ 10^6
Problem Explanationβ
The problem is to find all elements in an array except the two greatest elements and return them in sorted order. In simpler terms, you want to remove the two largest elements from the array and sort the remaining elements.
Code Implementationβ
- Python
- C++
- java
class Solution:
def findElements(self, a, n):
a.sort(); return a[0 : -2]
class Solution {
public:
vector<int> findElements(int a[], int n) {
sort(a, a + n);
vector <int> result;
for (int i = 0; i < n - 2; i++)
result.push_back(a[i]);
return result;
}
};
class Solution {
public long[] findElements( long a[], long n)
{
// Your code goes here
long[] ans=new long[a.length-2];
Arrays.sort(a);
for(int i=0;i<a.length-2;i++){
ans[i]=a[i];
}
return ans;
}
}