Next Greater Element in Java: Explanation & Practice

Find next greater element for each array element

Problem summary

For each element in the array, find the next greater element to its right. Use monotonic decreasing stack.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] nums = {4, 5, 2, 25};
        
        // Monotonic stack: keep decreasing elements
        // When we find a greater element, pop and assign
        // Print: 5 25 25 -1
    }
}

Expected output and test cases

  • [4,5,2,25]
    5 25 25 -1
  • [3,2,1] → all -1
    -1 -1 -1
  • [1,2,3]
    2 3 -1

Hints

  1. Use stack to store indices of elements waiting for their next greater
  2. For each new element, pop all smaller elements from stack
  3. Those popped elements found their next greater (current element)
  4. Push current element's index onto stack

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler