VOOZH about

URL: https://www.geeksforgeeks.org/dsa/next-greater-frequency-element/

⇱ Next Greater Frequency Element - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Next Greater Frequency Element

Last Updated : 12 Sep, 2025

Given an array arr[], for each element, find the first element to its right that appears more times in the array than the current element. If no such element exists, assign -1.

Examples: 

Input: arr[] = [2, 1, 1, 3, 2, 1]
Output: [1, -1, -1, 2, 1, -1]
Explanation: Frequencies: 1 → 3 times, 2 → 2 times, 3 → 1 time.
For arr[0] = 2, the next element 1 has a higher frequency → 1.
For arr[1] and arr[2] (1), no element to the right has a higher frequency → -1.
For arr[3] = 3, the next 2 has a higher frequency → 2.
For arr[4] = 2, the next 1 has a higher frequency → 1.
For arr[5] = 1, no elements to the right → -1.

Input: arr[] = [1, 2, 1]
Output: [-1, 1, -1]
Explanation: Frequencies: 1 → 2, 2 → 1.
2→1 (higher freq), others have no higher freq on right → [-1, 1, -1]

[Naive approach] Frequency Count and Nested Loop - O(n2) Time and O(n) Space

The idea is to find, for each element, the next element to its right that has a higher frequency using a frequency map and a nested loop. If none exists, return -1.


Output
1 -1 -1 2 1 -1 

[Efficient Approach] Frequency Counting and Stack - O(n) Time and O(n) Space

The idea is to use a frequency map to count occurrences, then apply a stack-based approach (similar to "Next Greater Element") to efficiently find the next element with a higher frequency for each position. For each element, we compare its frequency with elements tracked in the stack and update the result when a higher frequency is found.


Output
1 -1 -1 2 1 -1 
Comment
Article Tags:
Article Tags: