Find the next greater element in an array (in O(n) time)

For understanding the question, its variations and the possible solutions with detailed in depth explanation watch the video :

class NextGreaterChallenge {

    public static int[] nextGreaterElement(int[] arr) {

        int[] result = new int[arr.length];

        int resultIndex = 0;

        Stack<Integer> stack = new Stack<>(arr.length);
        //Iterate over the array from last
        for (int i = arr.length - 1; i >= 0; i--) {

            //Pop all the elements which are smaller than current element 
            if (!stack.isEmpty()) {
                while (!stack.isEmpty() && <= arr[i]) {
            //if stack becomes empty, then NGE doesn't exit 
                result[i] = -1;

            //If stack is not empty, NGE is top of stack 
                result[i]  =;

            //Push current element into stack


        return result;

Leave a Reply

Your email address will not be published.