![]() |
VOOZH | about |
Given an array of n distinct elements, the task is to find all elements in array which have at-least two greater elements than themselves.
Examples :
Input : arr[] = {2, 8, 7, 1, 5};
Output : 2 1 5
Explanation:
The output three elements have two or more greater elementsExplanation:
Input : arr[] = {7, -2, 3, 4, 9, -1};
Output : -2 3 4 -1
Method 1 (Simple): The naive approach is to run two loops and check one by one element of array check that array elements have at-least two elements greater than itself or not. If it's true then print array element.
Implementation:
2 -6 1
Time Complexity: O(n2)
Auxiliary Space: O(1).
Method 2 (Use Sorting): We sort the array first in increasing order, then we print first n-2 elements where n is size of array.
Implementation:
-6 1 2
Time Complexity: O(n Log n)
Auxiliary Space: O(1).
Method 3 (Efficient): In the second method we simply calculate the second maximum element of the array and print all element which is less than or equal to the second maximum.
Implementation:
2 -6 1
Time Complexity: O(n)
Auxiliary Space: O(1).