Next Greater Element

 Given an array arr[ ] of integers, the task is to find the next greater element for each element of the array in order of their appearance in the array. Next greater element of an element in the array is the nearest element on the right which is greater than the current element.

If there does not exist next greater of current element, then next greater element for current element is -1. For example, next greater of the last element is always -1.


Examples


Input: arr[] = [1, 3, 2, 4]

Output: [3, 4, 4, -1]

Explanation: The next larger element to 1 is 3, 3 is 4, 2 is 4 and for 4, since it doesn't exist, it is -1.

Input: arr[] = [6, 8, 0, 1, 3]

Output: [8, -1, 1, 3, -1]

Explanation: The next larger element to 6 is 8, for 8 there is no larger elements hence it is -1, for 0 it is 1 , for 1 it is 3 and then for 3 there is no larger element on right and hence -1.

Input: arr[] = [10, 20, 30, 50]

Output: [20, 30, 50, -1]

Explanation: For a sorted array, the next element is next greater element also except for the last element.

Input: arr[] = [50, 40, 30, 10]

Output: [-1, -1, -1, -1]

Explanation: There is no greater element for any of the elements in the array, so all are -1.


BruteForce Solution :o(n^2)


class Solution {
    public ArrayList<Integer> nextLargerElement(int[] arr) {
        // code here
       
       int n = arr.length; // size of the list
ArrayList<Integer> result = new ArrayList<>();

for (int i = 0; i < n; i++) {
    result.add(-1);
}

for(int i=0;i<n-1;i++)
{
    for(int j=i+1;j<n;j++)
    {
        if(arr[j]> arr[i])
        {
           result.set(i,arr[j]);
            break;
        }
    }
}
return result;
    }
}

Using Stack: O(n)


🧱 Step-by-Step Approach (Left to Right)

1. Create:

  • Stack<Integer> stack → to store indices.

  • int[] res → to store result, initialized with -1.

2. Traverse from left to right (i = 0 to n-1)

3. For each element arr[i]:

  • While the stack is not empty and arr[i] > arr[stack.peek()]:

    • Pop the index from the stack.

    • Set res[poppedIndex] = arr[i] because we found its next greater.

  • Push i onto the stack (because it might get its NGE later).


import java.util.*;

public class NextGreaterLeftToRight {
    public static int[] nextGreater(int[] arr) {
        int n = arr.length;
        int[] res = new int[n];
        Arrays.fill(res, -1); // default all to -1
        Stack<Integer> stack = new Stack<>(); // stores indices

        for (int i = 0; i < n; i++) {
            // Pop and resolve NGE for smaller elements
            while (!stack.isEmpty() && arr[i] > arr[stack.peek()]) {
                int index = stack.pop();
                res[index] = arr[i];
            }
            // Push current index to stack
            stack.push(i);
        }

        return res;
    }

    public static void main(String[] args) {
        int[] arr = {4, 5, 2, 10, 8};
        int[] result = nextGreater(arr);
        System.out.println(Arrays.toString(result)); // Output: [5, 10, 10, -1, -1]
    }
}


class Solution {
    public ArrayList<Integer> nextLargerElement(int[] arr) {
        // code here
        
          int n = arr.length;  // Define n before using it

        ArrayList<Integer> result= new ArrayList<>(Collections.nCopies(n,-1));
        Stack<Integer> st= new Stack<>();
        
        for(int i=0;i<arr.length;i++)
        {
            int num=arr[i];
            
            while(!st.isEmpty() && arr[i] > arr[st.peek()])
            {
                int popelement=st.pop();
                result.set(popelement,arr[i]); // set is used for update
            }
            st.push(i);
        }
        return result;
    }
}






Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence