Open In App

Generate an array consisting of most frequent greater elements present on the right side of each array element

Last Updated : 25 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array A[] of size N, the task is to generate an array B[] based on the following conditions:

  • For every array element A[i], find the most frequent element greater than A[i] present on the right of A[i]. Insert that element into B[].
  • If more than one such element is present on the right, choose the element having the smallest value.
  • If no element greater than A[i] is present on the right of A[i] then insert -1 into B[].

Finally, print the array B[] that is obtained.

Examples:

Input: A[] = {4, 5, 2, 25, 10, 5, 10, 3, 10, 5}
Output: 5, 10, 10, -1, -1, 10, -1, 5, -1, -1
Explanation:
A[0] (= 4): Array elements greater than 4 are {5, 25, 10}. Since 5 occurs maximum number of times, set B[0] = 5.
A[1] (= 5): Array elements greater than 5 are {25, 10}. Since 10 occurs maximum number of times, set B[1] = 10.
A[2] (= 2): Array elements greater than 2 are {5, 25, 10}. Since 10 occurs maximum number of times, set B[2] = 10.
A[3] (= 25): No element greater than A[3] found on its right. Therefore, set B[3] = -1.
A[4] (= 10): No element greater than A[4] found on its right. Therefore, set B[4] = -1.
Similarly, set B[5] = 10, B[6] = -1, B[7] = 5, B[8] = -1, B[9] = -1.
Therefore, the obtained array is B[] = {5, 10, 10, -1, -1, 10, -1, 5, -1, -1}.

Input: A[] = {1, 1, 3, 3, 2, 2}
Output: 2, 2, -1, -1, -1, -1

 

Naive Approach: Follow the steps below to solve the problem:

  • Initialize an array,  say V,  to store the resultant array elements.
  • Traverse the array A[] using a variable, say i, and perform the following operations:
    • Initialize variables ans as -1 and freq as 0, to store the result for the current index and its frequency.
    • Iterate over the range [i+1, N-1] using a variable, say j, and perform the following operations:
      • If the frequency of A[j] ≤ A[i], then continue.
      • Otherwise, check if the frequency of A[j] > freq. If found to be true, then update ans to A[j] and freq to the frequency of A[j].
      • Otherwise, if the frequency of A[j] is equal to freq, then update ans to a smaller value among A[j] and ans.
    • Insert the value of ans to the array, V.
  • Print the array, V as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to generate an array containing
// the most frequent greater element on the
// right side of each array element
void findArray(int arr[], int n)
{
    // Stores the generated array
    vector<int> v;
 
    // Traverse the array arr[]
    for (int i = 0; i < n; i++) {
 
        // Store the result for the
        // current index and its frequency
        int ans = -1, old_c = 0;
 
        // Iterate over the right subarray
        for (int j = i + 1; j < n; j++) {
 
            if (arr[j] > arr[i]) {
 
                // Store the frequency of
                // the current array element
                int curr_c
                    = count(&arr[j], &arr[n], arr[j]);
 
                // If the frequencies are equal
                if (curr_c == old_c) {
 
                    // Update ans to smaller
                    // of the two elements
                    if (arr[j] < ans)
                        ans = arr[j];
                }
 
                // If count of new element
                // is more than count of ans
                if (curr_c > old_c) {
                    ans = arr[j];
                    old_c = curr_c;
                }
            }
        }
 
        // Insert answer in the array
        v.push_back(ans);
    }
 
    // Print the resultant array
    for (int i = 0; i < v.size(); i++)
        cout << v[i] << " ";
}
 
// Driver Code
int main()
{
    // Given Input
    int arr[] = { 4, 5, 2, 25, 10, 5,
                  10, 3, 10, 5 };
    int size = sizeof(arr)
               / sizeof(arr[0]);
 
    findArray(arr, size);
 
    return 0;
}


Java




// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to generate an array containing
// the most frequent greater element on the
// right side of each array element
static void findArray(int arr[], int n)
{
     
    // Stores the generated array
    Vector<Integer> v = new Vector<Integer>();
     
    // Traverse the array arr[]
    for(int i = 0; i < n; i++)
    {
         
        // Store the result for the
        // current index and its frequency
        int ans = -1, old_c = 0;
         
        // Iterate over the right subarray
        for(int j = i + 1; j < n; j++)
        {
            if (arr[j] > arr[i])
            {
                 
                // Store the frequency of
                // the current array element
                int curr_c = 0;
                for(int k = j; k < n; k++)
                {
                    if (arr[k] == arr[j])
                    {
                        curr_c++;
                    }
                };
                 
                // If the frequencies are equal
                if (curr_c == old_c)
                {
                     
                    // Update ans to smaller
                    // of the two elements
                    if (arr[j] < ans)
                        ans = arr[j];
                }
                 
                // If count of new element
                // is more than count of ans
                if (curr_c > old_c)
                {
                    ans = arr[j];
                    old_c = curr_c;
                }
            }
        }
         
        // Insert answer in the array
        v.add(ans);
    }
     
    // Print the resultant array
    for(int i = 0; i < v.size(); i++)
        System.out.print(v.get(i) + " ");
}
 
// Driver Code
public static void main (String[] args)
{
 
    // Given Input
    int arr[] = { 4, 5, 2, 25, 10,
                  5, 10, 3, 10, 5 };
    int size = arr.length;
     
    findArray(arr, size);
}
}
 
// This code is contributed by jana_sayantan


Python3




# Python3 program for the above approach
 
# Function to generate an array containing
# the most frequent greater element on the
# right side of each array element
def findArray(arr, n):
     
    # Stores the generated array
    v = []
 
    # Traverse the array arr[]
    for i in range(n):
         
        # Store the result for the
        # current index and its frequency
        ans = -1
        old_c = 0
 
        # Iterate over the right subarray
        for j in range(i + 1, n):
            if (arr[j] > arr[i]):
 
                # Store the frequency of
                # the current array element
                curr_c = arr[j : n + 1].count(arr[j])
 
                # If the frequencies are equal
                if (curr_c == old_c):
 
                    # Update ans to smaller
                    # of the two elements
                    if (arr[j] < ans):
                        ans = arr[j]
 
                # If count of new element
                # is more than count of ans
                if (curr_c > old_c):
                    ans = arr[j]
                    old_c = curr_c
 
        # Insert answer in the array
        v.append(ans)
 
    # Print the resultant array
    for i in range(len(v)):
        print(v[i], end = " ")
 
# Driver Code
if __name__ == '__main__':
     
    # Given Input
    arr = [ 4, 5, 2, 25, 10,
            5, 10, 3, 10, 5 ]
    size = len(arr)
 
    findArray(arr, size)
 
# This code is contributed by mohit kumar 29


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to generate an array containing
// the most frequent greater element on the
// right side of each array element
static void findArray(int[] arr, int n)
{
     
    // Stores the generated array
    List<int> v = new List<int>();
     
    // Traverse the array arr[]
    for(int i = 0; i < n; i++)
    {
         
        // Store the result for the
        // current index and its frequency
        int ans = -1, old_c = 0;
         
        // Iterate over the right subarray
        for(int j = i + 1; j < n; j++)
        {
            if (arr[j] > arr[i])
            {
                 
                // Store the frequency of
                // the current array element
                int curr_c = 0;
                for(int k = j; k < n; k++)
                {
                    if (arr[k] == arr[j])
                    {
                        curr_c++;
                    }
                };
                 
                // If the frequencies are equal
                if (curr_c == old_c)
                {
                     
                    // Update ans to smaller
                    // of the two elements
                    if (arr[j] < ans)
                        ans = arr[j];
                }
                 
                // If count of new element
                // is more than count of ans
                if (curr_c > old_c)
                {
                    ans = arr[j];
                    old_c = curr_c;
                }
            }
        }
         
        // Insert answer in the array
        v.Add(ans);
    }
     
    // Print the resultant array
    for(int i = 0; i < v.Count; i++)
        Console.Write(v[i] + " ");
}
 
// Driver Code
public static void Main()
{
     
    // Given Input
    int[] arr= { 4, 5, 2, 25, 10,
                 5, 10, 3, 10, 5 };
    int size = arr.Length;
     
    findArray(arr, size);
}
}
 
// This code is contributed by sanjoy_62


Javascript




<script>
// Javascript program for the above approach
 
// Function to generate an array containing
// the most frequent greater element on the
// right side of each array element
function findArray(arr, n) {
    // Stores the generated array
    let v = new Array();
 
    // Traverse the array arr[]
    for (let i = 0; i < n; i++) {
 
        // Store the result for the
        // current index and its frequency
        let ans = -1, old_c = 0;
 
        // Iterate over the right subarray
        for (let j = i + 1; j < n; j++) {
 
            if (arr[j] > arr[i]) {
 
                // Store the frequency of
                // the current array element
                // let curr_c = count(&arr[j], &arr[n], arr[j]);
 
                let curr_c = 0;
                arr.slice(j, n).forEach((item) => { if (item == arr[j]) { curr_c++ } })
 
                // If the frequencies are equal
                if (curr_c == old_c) {
 
                    // Update ans to smaller
                    // of the two elements
                    if (arr[j] < ans)
                        ans = arr[j];
                }
 
                // If count of new element
                // is more than count of ans
                if (curr_c > old_c) {
                    ans = arr[j];
                    old_c = curr_c;
                }
            }
        }
 
        // Insert answer in the array
        v.push(ans);
    }
 
    // Print the resultant array
    for (let i = 0; i < v.length; i++)
        document.write(v[i] + " ");
}
 
// Driver Code
 
// Given Input
let arr = [4, 5, 2, 25, 10, 5,
    10, 3, 10, 5];
let size = arr.length
 
findArray(arr, size);
 
// This code is contributed by _saurabh_jaiswal
</script>


Output: 

5 10 10 -1 -1 10 -1 5 -1 -1

 

Time Complexity: O(N2), as we are using nested loops for traversing N*N times.
Auxiliary Space: O(N), as we are using extra space for storing generated array 

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads