DEV Community

Sadiul Hakim
Sadiul Hakim

Posted on

Algorithm part-1 : Next Greater Element Algorithm

Today i am going to start a new series about algorithms and problem solving. I'll be posting about various problems with their solution. I am going to use java as programming language.

Today i am going to show you How to solve next greater element problem in java.

Let's discuss this problem. In this problem we are given an integer array. We have to find exactly next greater element of each array element. If there is no greater element we will sit -1 at that position.

Example

We are given : [4,5,1,7,3,6,9]
Answer       : [5,7,7,9,6,9,-1]
Enter fullscreen mode Exit fullscreen mode

Let's see the solution...

public int[] nextGreater(int[] arr){
        int[] result=new int[arr.length];

        for(int i=0;i<arr.length;i++){
            int j=i+1;
            int value=arr[i];
            boolean got=false;
            while(j<=arr.length-1){
                if(arr[j] > value){
                    got=true;
                    result[i]=arr[j];
                    break;
                }                
                j++;

            }
            if(!got){
                result[i]=-1;
            }
        }


        return result;
    }
Enter fullscreen mode Exit fullscreen mode

Hope this algorithm works. Thank you ❤.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay