Introduction
The Next Element With Greater Frequency problem is a variation of the famous Next Greater Element (NGE) problem.
Instead of finding the next element with a greater value, we need to find the first element on the right whose frequency of occurrence in the entire array is greater than the frequency of the current element.
This problem combines two important concepts:
Hashing (to count frequencies)
Monotonic Stack (to efficiently find the next qualifying element)
Let's understand how to solve it in O(n) time.
Problem Statement
Given an array:
arr[]
For every element, find the first element on its right that has a higher frequency than the current element.
If no such element exists, return:
-1
for that position.
Example 1
Input
arr = [2, 1, 1, 3, 2, 1]
Frequency Table
1 → 3
2 → 2
3 → 1
Result
[1, -1, -1, 2, 1, -1]
Explanation
For:
arr[0] = 2
Frequency:
2
Next element having frequency greater than 2:
1
Frequency:
3
Hence answer:
1
Example 2
Input
[5,1,5,6,6]
Frequency Table
1 → 1
5 → 2
6 → 2
Output
[-1,5,-1,-1,-1]
For:
1
the next element:
5
has frequency:
2
Therefore answer:
5
Brute Force Approach
For every element:
Traverse all elements on the right.
Check frequencies.
Find the first element with greater frequency.
Pseudocode
for i = 0 to n-1
for j = i+1 to n-1
if freq[arr[j]] > freq[arr[i]]
answer = arr[j]
break
Complexity
O(n²)
This is too slow for:
n = 100000
Key Observation
This problem is almost identical to:
Next Greater Element
The only difference:
Instead of comparing values:
arr[j] > arr[i]
we compare frequencies:
freq[arr[j]] > freq[arr[i]]
Therefore, we can use a Monotonic Stack.
Frequency Map
First, count frequencies.
Example:
[2,1,1,3,2,1]
HashMap:
1 → 3
2 → 2
3 → 1
Now every frequency lookup becomes:
O(1)
Monotonic Stack Idea
Process elements from:
Right → Left
The stack stores candidate elements that may become answers.
For every element:
Remove all elements whose frequency is:
<= current frequency
because they cannot be the next greater frequency element.
The first remaining element on the stack becomes the answer.
Why Does This Work?
Consider:
arr = [2,1,1,3,2,1]
Frequencies:
2 → 2
1 → 3
3 → 1
Processing from right:
1
2
3
1
1
2
Whenever an element with lower or equal frequency appears, it gets removed because it cannot help future elements.
Thus every element is:
Pushed once
Popped once
giving O(n) complexity.

Join the conversation! Your thoughts help the community grow.