githubEdit

18. Next Element with Greater Frequency

βœ… GFG solution to find the next element with greater frequency using stack-based approach with frequency mapping for optimal performance. πŸš€

The problem can be found at the following link: πŸ”— Question Linkarrow-up-right

🧩 Problem Description

Given an array arr[] of integers, for each element, find the first element to its right that has a higher frequency than the current element. If no such element exists, return -1 for that position.

πŸ“˜ 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 combines Frequency Mapping with a Monotonic Stack technique to efficiently find the next greater frequency element:

Frequency Map + Monotonic Stack (Backward Traversal)

  1. Build Frequency Map:

    • Traverse the entire array once to count frequency of each element.

    • Store frequencies in an unordered map for O(1) lookup.

  2. Initialize Result and Stack:

    • Create result vector initialized with -1 for all positions.

    • Use stack to store indices in decreasing order of their frequencies.

  3. Backward Traversal:

    • Traverse array from right to left (n-1 to 0).

    • For current index i, compare frequency of arr[i] with stack top frequencies.

  4. Stack Maintenance:

    • Pop indices from stack while their frequency is less than or equal to current element's frequency.

    • If stack is not empty after popping, the top index gives the answer.

    • Push current index onto stack for future comparisons.

  5. Result Construction:

    • When a valid next greater frequency element is found, store its value in result array.

    • Otherwise, -1 remains as the default value.

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n), where n is the size of the array. The frequency map is built in O(n) time. Each element is pushed and popped from the stack at most once during the backward traversal, resulting in O(n) operations overall.

  • Expected Auxiliary Space Complexity: O(n), as we use a hash map to store frequencies of up to n distinct elements, a stack that can hold up to n indices in the worst case, and a result vector of size n.

πŸ§‘β€πŸ’» Code (C++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Forward Traversal Stack

πŸ’‘ Algorithm Steps:

  1. Build frequency map for all elements in the array.

  2. Traverse array from left to right using stack to track indices.

  3. For each element check if its frequency is greater than stack top frequency.

  4. Pop stack and assign current element as next greater frequency element.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Single pass with stack operations

  • Auxiliary Space: πŸ’Ύ O(n) - Stack and frequency map storage

βœ… Why This Approach?

  • Natural left to right processing

  • Clear monotonic stack pattern

  • Easy to understand and debug

πŸ“Š 3️⃣ Pair-Based Stack Tracking

πŸ’‘ Algorithm Steps:

  1. Create frequency map and store element-frequency pairs in stack.

  2. Process array from right to left maintaining decreasing frequency order.

  3. Pop all elements with frequency less than or equal to current element.

  4. Top of stack gives next greater frequency element for current position.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Linear time traversal

  • Auxiliary Space: πŸ’Ύ O(n) - Stack with pairs and map

βœ… Why This Approach?

  • Stores both element and frequency together

  • Avoids repeated map lookups during comparison

  • More cache-friendly for large datasets

πŸ“Š 4️⃣ Optimized Map Lookup

πŸ’‘ Algorithm Steps:

  1. Precompute frequencies and store in map for quick access.

  2. Use stack to maintain indices in order of processing.

  3. Compare frequencies directly using array indices stored in stack.

  4. Update result array when greater frequency element is found.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Each element processed once

  • Auxiliary Space: πŸ’Ύ O(n) - Stack and map storage

βœ… Why This Approach?

  • Minimal code with optimal performance

  • Standard monotonic stack implementation

  • Efficient for competitive programming

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🏷️ Backward Traversal

🟒 O(n)

🟑 O(n)

πŸš€ Right to left intuition

πŸ”§ Less common pattern

πŸ” Forward Traversal

🟒 O(n)

🟑 O(n)

πŸ“– Standard stack approach

πŸ’Ύ Same space as others

πŸ“Š Pair-Based Stack

🟒 O(n)

🟑 O(n)

🎯 Reduces map lookups

🐌 Extra pair storage overhead

πŸ”„ Optimized Lookup

🟒 O(n)

🟑 O(n)

⭐ Clean minimal code

πŸ”§ Similar to forward traversal

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Optimal performance needed

πŸ₯‡ Backward Traversal

β˜…β˜…β˜…β˜…β˜…

πŸ“– Readability priority

πŸ₯ˆ Forward Traversal

β˜…β˜…β˜…β˜…β˜…

πŸ”§ Cache optimization

πŸ₯‰ Pair-Based Stack

β˜…β˜…β˜…β˜…β˜†

🎯 Interview/Competitive

πŸ… Optimized Lookup

β˜…β˜…β˜…β˜…β˜…

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated