08. Next Element with Greater Frequency
β GFG solution to the Next Element with Greater Frequency problem: find the closest element to the right with higher frequency using monotonic stack technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given an array arr[]
of integers, for each element, find the closest (distance wise) to its right that has a higher frequency than the current element. If no such element exists, return -1 for that position.
The goal is to efficiently find the next element with greater frequency for each position in the array while maintaining optimal time and space complexity.
π Examples
Example 1
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], no element to the right has a higher frequency β -1.
For arr[3] = 3, the next element 2 has a higher frequency β 2.
For arr[4] = 2, the next element 1 has a higher frequency β 1.
For arr[5] = 1, no elements to the right β -1.
Example 2
Input: arr[] = [5, 1, 5, 6, 6]
Output: [-1, 5, -1, -1, -1]
Explanation: Frequencies: 1 β 1 time, 5 β 2 times, 6 β 2 times.
For arr[0] and arr[2], no element to the right has a higher frequency β -1.
For arr[1] = 1, the next element 5 has a higher frequency β 5.
For arr[3] and arr[4], no element to the right has a higher frequency β -1.
π Constraints
$1 \le \text{arr.size()} \le 10^5$
$1 \le \text{arr}[i] \le 10^5$
β
My Approach
The optimal approach uses a Monotonic Stack combined with Frequency Mapping to efficiently find the next element with greater frequency:
Forward Stack + Map
Pre-compute Frequencies:
Build a frequency map to store count of each element in the array.
This allows O(1) frequency lookup for any element.
Initialize Data Structures:
Use a stack to maintain indices of elements in decreasing order of their frequencies.
Initialize result array with -1 values.
Process Elements Left to Right:
For each element at index
i
, compare its frequency with elements in the stack.While stack is not empty and current element's frequency > frequency of element at stack top:
Pop the index from stack and set result[popped_index] = current_element.
Push current index onto stack.
Stack Invariant:
Stack maintains indices in decreasing order of frequencies.
When we find an element with higher frequency, it becomes the answer for all elements in stack with lower frequencies.
Final Result:
Elements remaining in stack have no next greater frequency element (already -1 in result).
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the size of the array. Each element is pushed and popped from the stack at most once, and frequency lookup is O(1).
Expected Auxiliary Space Complexity: O(n), where n is the size of the array. We use O(n) space for the frequency map, O(n) for the stack in worst case, and O(n) for the result array.
π§βπ» Code (C++)
class Solution {
public:
vector<int> findGreater(vector<int>& a) {
unordered_map<int, int> f;
for (int x : a) f[x]++;
vector<int> r(a.size(), -1);
stack<int> s;
for (int i = 0; i < a.size(); i++) {
while (!s.empty() && f[a[i]] > f[a[s.top()]]) {
r[s.top()] = a[i];
s.pop();
}
s.push(i);
}
return r;
}
};
π§βπ» Code (Java)
class Solution {
public ArrayList<Integer> findGreater(int[] a) {
HashMap<Integer, Integer> f = new HashMap<>();
for (int x : a) f.put(x, f.getOrDefault(x, 0) + 1);
ArrayList<Integer> r = new ArrayList<>(Collections.nCopies(a.length, -1));
Deque<Integer> s = new ArrayDeque<>();
for (int i = 0; i < a.length; i++) {
while (!s.isEmpty() && f.get(a[i]) > f.get(a[s.peekLast()]))
r.set(s.pollLast(), a[i]);
s.add(i);
}
return r;
}
}
π Code (Python)
from collections import Counter
class Solution:
def findGreater(self, a):
f = Counter(a)
r, s = [-1]*len(a), []
for i, v in enumerate(a):
while s and f[v] > f[a[s[-1]]]:
r[s.pop()] = v
s.append(i)
return r
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated