Given an array arr of distinct elements, the task is to return an array of elements that have at least two greater elements.
Examples:
Input: arr[] = [2, 8, 7, 1, 5]
Output: [1, 2, 5]
Explanation: Here we return an array contains 1, 2, 5 and we leave two greatest elements 7 & 8.Input: arr[] = [7, -2, 3, 4, 9, -1]
Output: [-2, -1, 3, 4]
Explanation: Here we return an array contains -2 , -1, 3, 4 and we leave two greatest elements 7 & 9.
Table of Content
[Naive Approach] Sorting and Storing the Result - O(n log n) Time and O(n) Space
The idea is to sort the array in ascending order and store all elements except the last two elements in a separate result array. The last two elements after sorting are the two greatest elements.
Working of Approach:
- Sort the given array in ascending order.
- Create a result vector res.
- Traverse the sorted array from index 0 to n - 3.
- Add each element to the result vector.
- Return the result vector.
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
// Function to find elements in an array except for the last two elements.
vector<int> findElements(vector<int> arr)
{
int n = arr.size();
// Sorting the array in ascending order.
sort(arr.begin(), arr.end());
// Creating a vector to store the elements.
vector<int> res;
// Iterating over the array except for the last two elements.
for (int i = 0; i < n - 2; i++)
{
// Adding the current element to the result vector.
res.push_back(arr[i]);
}
// Returning the required elements.
return res;
}
int main()
{
vector<int> arr = {7, -2, 3, 4, 9, -1};
vector<int> res = findElements(arr);
cout << "[";
for (int i = 0; i < res.size(); i++)
{
cout << res[i];
if (i < res.size() - 1)
{
cout << ", ";
}
}
cout << "]" << endl;
return 0;
}
import java.util.*;
class GFG {
// Function to find elements in an array except for the
// last two elements.
public long[] findElements(long[] arr)
{
int n = arr.length;
// Sorting the array in ascending order.
Arrays.sort(arr);
// Creating an array to store the elements.
long[] res = new long[n - 2];
// Iterating over the array except for the last two
// elements.
for (int i = 0; i < n - 2; i++) {
res[i] = arr[i];
}
// Returning the required elements.
return res;
}
public static void main(String[] args)
{
long[] arr = { 2, 8, 7, 1, 5 };
GFG obj = new GFG();
long[] res = obj.findElements(arr);
System.out.print("[");
for (int i = 0; i < res.length; i++) {
System.out.print(res[i]);
if (i < res.length - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
}
"""
Function to find elements in an array except for the last two elements.
"""
def findElements(arr):
n = len(arr)
# Sorting the array in ascending order.
sortedArr = sorted(arr)
# Creating a list to store the elements.
res = []
# Iterating over the array except for the last two elements.
for i in range(n - 2):
# Adding the current element to the result list.
res.append(sortedArr[i])
# Returning the required elements.
return res
if __name__ == "__main__":
arr = [7, -2, 3, 4, 9, -1]
res = findElements(arr)
print(res)
using System;
class GFG {
// Function to find elements in an array except for the
// last two elements.
public int[] findElements(int[] arr)
{
int n = arr.Length;
// Sorting the array in ascending order.
Array.Sort(arr);
// Creating an array to store the elements.
int[] res = new int[n - 2];
// Iterating over the array except for the last two
// elements.
for (int i = 0; i < n - 2; i++) {
// Adding the current element to the result
// array.
res[i] = arr[i];
}
// Returning the required elements.
return res;
}
static void Main(string[] args)
{
int[] arr = { 7, -2, 3, 4, 9, -1 };
GFG obj = new GFG();
int[] res = obj.findElements(arr);
Console.Write("[");
for (int i = 0; i < res.Length; i++) {
Console.Write(res[i]);
if (i < res.Length - 1) {
Console.Write(", ");
}
}
Console.WriteLine("]");
}
}
// Function to find elements in an array except for the last
// two elements.
function findElements(arr)
{
let n = arr.length;
// Sorting the array in ascending order.
let sortedArr = arr.slice().sort();
// Creating an array to store the elements.
let res = [];
// Iterating over the array except for the last two
// elements.
for (let i = 0; i < n - 2; i++) {
// Adding the current element to the result array.
res.push(sortedArr[i]);
}
// Returning the required elements.
return res;
}
// Function to find elements in an array except for the last
// two elements.
function findElements(arr)
{
let n = arr.length;
// Sorting the array in ascending order.
let sortedArr = arr.slice().sort((a, b) => a - b);
// Creating an array to store the elements.
let res = [];
// Iterating over the array except for the last two
// elements.
for (let i = 0; i < n - 2; i++) {
// Adding the current element to the result array.
res.push(sortedArr[i]);
}
// Returning the required elements.
return res;
}
// Driver Code
let arr = [ 2, 8, 7, 1, 5 ];
let res = findElements(arr);
console.log("[" + res.join(", ") + "]");
Output
[-2, -1, 3, 4]
[Expected Approach] Sorting and Removing the Last Two Elements - O(n log n) Time and O(1) Space
The idea is to sort the array in ascending order and directly remove the last two elements. Since they are the two greatest elements, the remaining array is the required answer.
Working of Approach:
- Sort the given array in ascending order.
- The last two elements are the two greatest elements.
- Resize the array to remove these two elements.
- The remaining elements are already in sorted order.
- Return the modified array.
Let us understand with an example:
Input: arr[] = [7, -2, 3, 4, 9, -1]
- First, sort the array: [-2, -1, 3, 4, 7, 9].
- The last two elements, 7 and 9, are the two greatest elements.
- Resize the array to keep only the first n - 2 elements.
- The modified array becomes [-2, -1, 3, 4].
- Finally, return the modified array.
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
// Function to find elements in an array except for the last two elements.
vector<int> findElements(vector<int> arr)
{
// Sorting the array in ascending order.
sort(arr.begin(), arr.end());
// Removing the last two greatest elements.
arr.resize(arr.size() - 2);
// Returning the required elements.
return arr;
}
int main()
{
vector<int> arr = {7, -2, 3, 4, 9, -1};
vector<int> res = findElements(arr);
cout << "[";
for (int i = 0; i < res.size(); i++)
{
cout << res[i];
if (i < res.size() - 1)
{
cout << ", ";
}
}
cout << "]" << endl;
return 0;
}
import java.util.*;
class GFG {
// Function to find elements in an array except for the
// last two elements.
public long[] findElements(long[] arr)
{
// Sorting the array in ascending order.
Arrays.sort(arr);
// Removing the last two greatest elements.
arr = Arrays.copyOf(arr, arr.length - 2);
// Returning the required elements.
return arr;
}
public static void main(String[] args)
{
long[] arr = { 2, 8, 7, 1, 5 };
GFG obj = new GFG();
long[] res = obj.findElements(arr);
System.out.print("[");
for (int i = 0; i < res.length; i++) {
System.out.print(res[i]);
if (i < res.length - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
}
# Function to find elements in an array except for the last two elements.
def findElements(arr):
# Sorting the array in ascending order.
arr.sort()
# Removing the last two greatest elements.
del arr[-2:]
# Returning the required elements.
return arr
if __name__ == "__main__":
arr = [2, 8, 7, 1, 5]
res = findElements(arr)
print(res)
using System;
class GFG {
// Function to find elements in an array except for the
// last two elements.
public int[] findElements(int[] arr)
{
// Sorting the array in ascending order.
Array.Sort(arr);
// Removing the last two greatest elements.
Array.Resize(ref arr, arr.Length - 2);
// Returning the required elements.
return arr;
}
static void Main(string[] args)
{
int[] arr = { 2, 8, 7, 1, 5 };
GFG obj = new GFG();
int[] res = obj.findElements(arr);
Console.Write("[");
for (int i = 0; i < res.Length; i++) {
Console.Write(res[i]);
if (i < res.Length - 1) {
Console.Write(", ");
}
}
Console.WriteLine("]");
}
}
// Function to find elements in an array except for the last
// two elements.
function findElements(arr)
{
// Sorting the array in ascending order.
arr.sort((a, b) => a - b);
// Removing the last two greatest elements.
arr = arr.slice(0, arr.length - 2);
// Returning the required elements.
return arr;
}
// Driver Code
let arr = [ 2, 8, 7, 1, 5 ];
let res = findElements(arr);
console.log("[" + res.join(", ") + "]");
Output
[-2, -1, 3, 4]
[Alternate Approach] Find Two Greatest Elements and Sort the Remaining Elements - O(n log n) Time and O(n) Space
The idea is to find the greatest and second greatest elements without sorting the array. Then, exclude these two elements, sort all the remaining elements, and return them in ascending order.
Working of the Approach:
- Traverse the array to find the greatest and second greatest elements.
- Create a result vector to store the remaining elements.
- Traverse the array again and exclude the two greatest elements.
- Add all other elements to the result vector.
- Sort the result vector and return it.
#include <algorithm>
#include <climits>
#include <iostream>
#include <vector>
using namespace std;
// Function to find elements except the two greatest elements.
vector<int> findElements(vector<int> arr)
{
int n = arr.size();
// Initializing the greatest and second greatest elements.
int first = INT_MIN;
int second = INT_MIN;
// Finding the greatest and second greatest elements.
for (int i = 0; i < n; i++)
{
if (arr[i] > first)
{
second = first;
first = arr[i];
}
else if (arr[i] > second)
{
second = arr[i];
}
}
// Creating a vector to store the remaining elements.
vector<int> res;
// Adding all elements except the two greatest elements.
for (int i = 0; i < n; i++)
{
if (arr[i] != first && arr[i] != second)
{
res.push_back(arr[i]);
}
}
// Sorting the remaining elements.
sort(res.begin(), res.end());
// Returning the required elements.
return res;
}
int main()
{
vector<int> arr = {7, -2, 3, 4, 9, -1};
vector<int> res = findElements(arr);
cout << "[";
for (int i = 0; i < res.size(); i++)
{
cout << res[i];
if (i < res.size() - 1)
{
cout << ", ";
}
}
cout << "]" << endl;
return 0;
}
import java.util.*;
class GFG {
// Function to find elements except the two greatest
// elements.
public long[] findElements(long[] arr)
{
int n = arr.length;
// Initializing the greatest and second greatest
// elements.
long first = Long.MIN_VALUE;
long second = Long.MIN_VALUE;
// Finding the greatest and second greatest
// elements.
for (int i = 0; i < n; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
}
else if (arr[i] > second) {
second = arr[i];
}
}
// Creating a list to store the remaining elements.
ArrayList<Long> list = new ArrayList<>();
// Adding all elements except the two greatest
// elements.
for (int i = 0; i < n; i++) {
if (arr[i] != first && arr[i] != second) {
list.add(arr[i]);
}
}
// Sorting the remaining elements.
Collections.sort(list);
// Creating the result array.
long[] res = new long[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
// Returning the required elements.
return res;
}
public static void main(String[] args)
{
long[] arr = { 2, 8, 7, 1, 5 };
GFG obj = new GFG();
long[] res = obj.findElements(arr);
System.out.print("[");
for (int i = 0; i < res.length; i++) {
System.out.print(res[i]);
if (i < res.length - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
}
def findElements(arr):
# Initializing the greatest and second greatest elements.
n = len(arr)
first = float('-inf')
second = float('-inf')
# Finding the greatest and second greatest elements.
for i in range(n):
if arr[i] > first:
second = first
first = arr[i]
elif arr[i] > second:
second = arr[i]
# Creating a list to store the remaining elements.
res = []
# Adding all elements except the two greatest elements.
for i in range(n):
if arr[i] != first and arr[i] != second:
res.append(arr[i])
# Sorting the remaining elements.
res.sort()
# Returning the required elements.
return res
if __name__ == '__main__':
arr = [2, 8, 7, 1, 5]
res = findElements(arr)
print('[' + ', '.join(map(str, res)) + ']')
using System;
using System.Collections.Generic;
class GFG {
// Function to find elements except the two greatest
// elements.
public int[] findElements(int[] arr)
{
int n = arr.Length;
// Initializing the greatest and second greatest
// elements.
int first = int.MinValue;
int second = int.MinValue;
// Finding the greatest and second greatest
// elements.
for (int i = 0; i < n; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
}
else if (arr[i] > second) {
second = arr[i];
}
}
// Creating a list to store the remaining elements.
List<int> list = new List<int>();
// Adding all elements except the two greatest
// elements.
for (int i = 0; i < n; i++) {
if (arr[i] != first && arr[i] != second) {
list.Add(arr[i]);
}
}
// Sorting the remaining elements.
list.Sort();
// Creating the result array.
int[] res = list.ToArray();
// Returning the required elements.
return res;
}
static void Main(string[] args)
{
int[] arr = { 2, 8, 7, 1, 5 };
GFG obj = new GFG();
int[] res = obj.findElements(arr);
Console.Write("[");
for (int i = 0; i < res.Length; i++) {
Console.Write(res[i]);
if (i < res.Length - 1) {
Console.Write(", ");
}
}
Console.WriteLine("]");
}
}
function findElements(arr)
{
// Initializing the greatest and second greatest
// elements.
let n = arr.length;
let first = Number.NEGATIVE_INFINITY;
let second = Number.NEGATIVE_INFINITY;
// Finding the greatest and second greatest elements.
for (let i = 0; i < n; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
}
else if (arr[i] > second) {
second = arr[i];
}
}
// Creating an array to store the remaining elements.
let res = [];
// Adding all elements except the two greatest elements.
for (let i = 0; i < n; i++) {
if (arr[i] !== first && arr[i] !== second) {
res.push(arr[i]);
}
}
// Sorting the remaining elements.
res.sort((a, b) => a - b);
// Returning the required elements.
return res;
}
// Driver Code
let arr = [ 2, 8, 7, 1, 5 ];
let res = findElements(arr);
console.log(`[${res.join(", ")}]`);
Output
[-2, -1, 3, 4]