710279. Next element with greater frequency

Medium

Next Element with Greater Frequency

Summary

Given an array of elements and their frequencies, find the next element that has a greater frequency than the current one. This problem involves working with data structures like arrays and hash maps to efficiently solve the problem.

Detailed Explanation

To solve this problem, we will use a stack-based approach. We start by iterating through the array and its frequencies. For each element, we check if it has a greater frequency than the top of our stack (which represents the previous elements). If it does, we push it onto the stack. This process allows us to efficiently keep track of elements with decreasing frequencies.

Here's a step-by-step breakdown:

  1. Initialize an empty stack.
  2. Iterate through the array and its frequencies.
  3. For each element, check if it has a greater frequency than the top of our stack (if the stack is not empty).
  4. If it does, push it onto the stack.
  5. When we finish iterating through the array, the top of our stack will contain the next element with a greater frequency.

Time complexity: O(n), where n is the number of elements in the array. Space complexity: O(n), as we need to store all elements and their frequencies in memory.

Here's an ASCII art diagram illustrating this process:

  Stack: []          Array: [a, b, c, d]
  Frequency: [1, 2, 3, 4]
  Iterate through array:
  a (freq = 1) -> push to stack
  b (freq = 2) -> check top of stack, no match, move on
  c (freq = 3) -> check top of stack, match, do nothing
  d (freq = 4) -> check top of stack, match, do nothing

  Stack: [a]          Array: [e, f]
  Frequency: [1, 5, 6]

  Iterate through array:
  e (freq = 5) -> push to stack
  f (freq = 6) -> check top of stack, no match, move on

  Stack: [a, e]      Array: [g]
  Frequency: [1, 5, 6, 7]

  Iterate through array:
  g (freq = 7) -> push to stack

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.Stack;

public class NextElement {
    public static int nextGreaterFrequency(int[] arr, int[] freq) {
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < arr.length; i++) {
            while (!stack.isEmpty() && freq[stack.peek()] <= freq[i]) {
                stack.pop();
            }
            if (!stack.isEmpty()) {
                return arr[stack.peek()];
            } else {
                return -1;
            }
        }
        return -1;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.