How to find the Next Greater element in java?

               An array of integers is given. You have to find the next greater element for each element in the array.  This is one of the interview question in java.

Let us find the solution for this problem.

  • ·       First, write a class with main function. next, declare an array with some ‘no’ of elements.
  • ·       Create a stack with new object “stack1”.
  • ·       Check the current element of the array with other elements for greater value. If the value is less, then delete the elements. 
  • ·       If the value is greater than the current element, push the current element to stack. otherwise, insert -1 value to stack.
  • ·       Finally, print the value. If stack is null, then there is no greater number.

Program:

import java.util.Stack;

public class NextGElement {

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

        int no = arr.length;

        int[] result1 = new int[no];

        Stack<Integer> stack1 = new Stack<>();

        for (int i = no - 1; i >= 0; i--) {

            // delete the elements which are less than or equal to the current element

            while (!stack1.isEmpty() && stack1.peek() <= arr[i]) {

                stack1.pop();

            }

            // If stack is null, there is no bigger number

            result1[i] = stack1.isEmpty() ? -1 : stack1.peek();

            // insert the current element to the stack

            stack1.push(arr[i]);

        }

        return result1;

    }

    public static void main(String[] args) {

        int[] arr1 = {234, 345, 20,530,56};

        int[] result1 = nextGElements(arr1);

         // let us display the output

        System.out.print("The Next Greater Elements are: ");

        for (int value : result1) {

            System.out.print(value + " ");

        }

    }

}

Compile and run the program to get the output.

Here, is the output.

C:\raji\blog>javac NextGElement.java

C:\raji\blog>java NextGElement

The Next Greater Elements are: 345 530 530 -1 -1

Using the above logic, it is easy to implement the next greater element problem in java. Happy coding!!!

No comments:

Post a Comment