Open In App

Next Greater Frequency Element

Last Updated : 04 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array, for each element find the value of the nearest element to the right which is having a frequency greater than that of the current element. If there does not exist an answer for a position, then make the value '-1'.

Examples: 

Input: arr[] = [2, 1, 1, 3, 2, 1]
Output: [1, -1, -1, 2, 1, -1]
Explanation: 1 appears 3 times, 2 appears 2 times and 3 appears 1 time.
For arr[0] ie, 2 arr[1] ie 1 is the closest element on its right which has greater frequency than the frequency of 2.
For the arr[1] and arr[2] no element on the right has greater frequency than 1, so -1 will be printed. and so on.

Input: arr[] = [5, 1, 2, 3, 2, 5, 5, 4, 5, 2]
Output: [-1, 2, 5, 2, 5, -1, -1, 5, -1, -1]

[Naive approach] Frequency Count and Nested Loop - O(n^2) time and O(n) space

Steps to solve:

1. Frequency Calculation: The first step is to calculate the frequency of each element in the array. We can use a hash map or an array (if elements are within a fixed range) to store the count of occurrences for each element. This step requires only one traversal of the array, making it efficient.

2. Outer Loop (Iterate Through the Array): After calculating the frequencies, we begin iterating over each element in the array. For each element, we need to find the first element in the remaining part of the array that has a higher frequency than the current element.

3. Inner Loop (Find Greater Frequency): For each element picked by the outer loop, the inner loop searches through the remaining elements to find one whose frequency is greater. If such an element is found, it is printed. If no element is found with a higher frequency, -1 is printed for that element.

4. Output: After processing each element, we collect the results. The output for each element is either the first element with a higher frequency or -1 if no such element exists.

C++
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

vector<int> findGreater(const vector<int>& arr) {
    
    // Step 1: Calculate frequency of each element
    // using a hash map (unordered_map).
    unordered_map<int, int> freq;
    for (int num : arr) {
        freq[num]++;
    }

    vector<int> result;

    // Step 2: Iterate over the array using two loops
    for (int i = 0; i < arr.size(); i++) {
        bool found = false;

        // Inner loop to find the first element 
        // with a greater frequency
        for (int j = i + 1; j < arr.size(); j++) {
            if (freq[arr[j]] > freq[arr[i]]) {
                result.push_back(arr[j]);
                found = true;
                break;
            }
        }

        // If no element with a greater frequency 
        // is found, push -1
        if (!found) {
            result.push_back(-1);
        }
    }

    return result;
}

int main() {
    vector<int> arr = {2, 1, 1, 3, 2, 1}; 
    vector<int> result = findGreater(arr); 

    
    for (int num : result) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}
Java
import java.util.*;

public class GfG {
    public static int[] findGreater(int[] arr) {
        
        // Step 1: Calculate frequency of each element using a hash map.
        Map<Integer, Integer> freq = new HashMap<>();
        for (int num : arr) {
            freq.put(num, freq.getOrDefault(num, 0) + 1);
        }

        int[] result = new int[arr.length];

        // Step 2: Iterate over the array using two loops
        for (int i = 0; i < arr.length; i++) {
            boolean found = false;

            // Inner loop to find the first element with a greater frequency
            for (int j = i + 1; j < arr.length; j++) {
                if (freq.get(arr[j]) > freq.get(arr[i])) {
                    result[i] = arr[j];
                    found = true;
                    break;
                }
            }

            // If no element with a greater frequency 
            // is found, set -1
            if (!found) {
                result[i] = -1;
            }
        }

        return result;
    }

    public static void main(String[] args) {
        int[] arr = {2, 1, 1, 3, 2, 1}; 
        int[] result = findGreater(arr); 

        for (int num : result) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}
Python
from collections import Counter

def findGreater(arr):
    
    # Step 1: Calculate frequency of each 
    # element using Counter.
    freq = Counter(arr)
    result = []

    # Step 2: Iterate over the array using two loops
    for i in range(len(arr)):
        found = False

        # Inner loop to find the first element 
        # with a greater frequency
        for j in range(i + 1, len(arr)):
            if freq[arr[j]] > freq[arr[i]]:
                result.append(arr[j])
                found = True
                break

        # If no element with a greater frequency 
        # is found, append -1
        if not found:
            result.append(-1)

    return result

arr = [2, 1, 1, 3, 2, 1]
result = findGreater(arr)
print(' '.join(map(str, result)))
C#
using System;
using System.Collections.Generic;

class GfG {
    public static int[] FindGreater(int[] arr) {
        
        // Step 1: Calculate frequency of each element 
        // using a dictionary.
        Dictionary<int, int> freq = new Dictionary<int, int>();
        foreach (int num in arr) {
            if (freq.ContainsKey(num)) {
                freq[num]++;
            } else {
                freq[num] = 1;
            }
        }

        int[] result = new int[arr.Length];

        // Step 2: Iterate over the array using two loops
        for (int i = 0; i < arr.Length; i++) {
            bool found = false;

            // Inner loop to find the first element with
            // a greater frequency
            for (int j = i + 1; j < arr.Length; j++) {
                if (freq[arr[j]] > freq[arr[i]]) {
                    result[i] = arr[j];
                    found = true;
                    break;
                }
            }

            // If no element with a greater frequency is found, set -1
            if (!found) {
                result[i] = -1;
            }
        }

        return result;
    }

    static void Main() {
        int[] arr = {2, 1, 1, 3, 2, 1}; 
        int[] result = FindGreater(arr);

        Console.WriteLine(string.Join(" ", result));
    }
}
JavaScript
function findGreater(arr) {
    
    // Step 1: Calculate frequency of each element using an object.
    const freq = {};
    arr.forEach(num => {
        freq[num] = (freq[num] || 0) + 1;
    });

    const result = [];

    // Step 2: Iterate over the array using two loops
    for (let i = 0; i < arr.length; i++) {
        let found = false;

        // Inner loop to find the first element with a greater frequency
        for (let j = i + 1; j < arr.length; j++) {
            if (freq[arr[j]] > freq[arr[i]]) {
                result.push(arr[j]);
                found = true;
                break;
            }
        }

        // If no element with a greater frequency is found, push -1
        if (!found) {
            result.push(-1);
        }
    }

    return result;
}

const arr = [2, 1, 1, 3, 2, 1];
const result = findGreater(arr);
console.log(result.join(' '));

Output
1 -1 -1 2 1 -1 

[Efficient Approach] Frequency Counting and Stack - O(n) time and O(n) space

First, a frequency map is created to store how often each element appears in the array. After we build the map, this problems becomes similar to next greater element as finding frequency becomes O(1) task. For each element, we compare its frequency with the element at the top of the stack. If the current element has a higher frequency, it becomes the next greater frequency element for the top of the stack. If no such element exists, -1 is assigned.

C++
#include <iostream>
#include <stack>
#include <vector>
#include <map>

using namespace std;

void nextGreaterFrequency(const vector<int>& arr) {
    int n = arr.size();
    map<int, int> freq;
    
    // Step 1: Build frequency map
    for (auto it : arr) {
        freq[it]++;
    }

    vector<int> res(n, -1);    // Initialize res with -1
    stack<int> s;              // Stack to store indexes

    // Step 2: Traverse elements
    for (int i = 0; i < n; i++) {
        
        // While current frequency is 
        // greater than frequency at stack top
        while (!s.empty() && freq[arr[i]] > freq[arr[s.top()]]) {
            res[s.top()] = arr[i];
            s.pop();
        }
        s.push(i);
    }

    // Step 3: Output the res
    for (auto x : res) {
        cout << x << " ";
    }
}

int main() {
    vector<int> arr = {2, 1, 1, 3, 2, 1};
    nextGreaterFrequency(arr);
    return 0;
}
Java
import java.util.*;

public class Main {
    public static void nextGreaterFrequency(int[] arr) {
        int n = arr.length;
        Map<Integer, Integer> freq = new HashMap<>();

        // Step 1: Build frequency map
        for (int num : arr) {
            freq.put(num, freq.getOrDefault(num, 0) + 1);
        }

        int[] res = new int[n]; // Initialize res with -1
        Arrays.fill(res, -1);
        Stack<Integer> s = new Stack<>(); // Stack to store indexes

        // Step 2: Traverse elements
        for (int i = 0; i < n; i++) {
            
            // While current frequency is 
            // greater than frequency at stack top
            while (!s.isEmpty() && freq.get(arr[i]) > freq.get(arr[s.peek()])) {
                res[s.pop()] = arr[i];
            }
            s.push(i);
        }

        // Step 3: Output the res
        for (int x : res) {
            System.out.print(x + " ");
        }
    }

    public static void main(String[] args) {
        int[] arr = {2, 1, 1, 3, 2, 1};
        nextGreaterFrequency(arr);
    }
}
Python
def next_greater_frequency(arr):
    n = len(arr)
    freq = {}

    # Step 1: Build frequency map
    for num in arr:
        freq[num] = freq.get(num, 0) + 1

    res = [-1] * n  # Initialize res with -1
    s = []  # Stack to store indexes

    # Step 2: Traverse elements
    for i in range(n):
        
        # While current frequency is 
        # greater than frequency at stack top
        while s and freq[arr[i]] > freq[arr[s[-1]]]:
            res[s.pop()] = arr[i]
        s.append(i)

    # Step 3: Output the res
    print(' '.join(map(str, res)))

arr = [2, 1, 1, 3, 2, 1]
next_greater_frequency(arr)
C#
using System;
using System.Collections.Generic;

class Program {
    static void NextGreaterFrequency(int[] arr) {
        int n = arr.Length;
        Dictionary<int, int> freq = new Dictionary<int, int>();

        // Step 1: Build frequency map
        foreach (var num in arr) {
            if (freq.ContainsKey(num)) freq[num]++;
            else freq[num] = 1;
        }

        int[] res = new int[n]; // Initialize res with -1
        Array.Fill(res, -1);
        Stack<int> s = new Stack<int>(); // Stack to store indexes

        // Step 2: Traverse elements
        for (int i = 0; i < n; i++) {
            
            // While current frequency is 
            // greater than frequency at stack top
            while (s.Count > 0 && freq[arr[i]] > freq[arr[s.Peek()]]) {
                res[s.Pop()] = arr[i];
            }
            s.Push(i);
        }

        // Step 3: Output the res
        Console.WriteLine(string.Join(" ", res));
    }

    static void Main() {
        int[] arr = {2, 1, 1, 3, 2, 1};
        NextGreaterFrequency(arr);
    }
}
JavaScript
function nextGreaterFrequency(arr) {
    let n = arr.length;
    let freq = {};

    // Step 1: Build frequency map
    for (let num of arr) {
        freq[num] = (freq[num] || 0) + 1;
    }

    let res = new Array(n).fill(-1); // Initialize res with -1
    let s = []; // Stack to store indexes

    // Step 2: Traverse elements
    for (let i = 0; i < n; i++) {
        
        // While current frequency is 
        // greater than frequency at stack top
        while (s.length > 0 && freq[arr[i]] > freq[arr[s[s.length - 1]]]) {
            res[s.pop()] = arr[i];
        }
        s.push(i);
    }

    // Step 3: Output the res
    console.log(res.join(' '));
}

let arr = [2, 1, 1, 3, 2, 1];
nextGreaterFrequency(arr);

Output
1 -1 -1 2 1 -1 


Next Article
Article Tags :
Practice Tags :

Similar Reads