Prepin
Log in

For a given array, output the Next Greater Element (NGE) for each element. The NGE for an element x is defined as the first element to the right of x in the array that is greater than x. If there is no greater element available, treat the NGE as -1.

Approach / Explanation

This question presents you with an array of integers. For each element in the array, your task is to identify and print the first element that is greater than it and appears to its right. If no such element exists, you should print -1. To tackle this question, keep the following two important points in mind: You must iterate through the array, and for each element, perform another iteration from that index to the end of the array to find the next greater element. If you find it, print that element; if not, print -1. The term 'next' greater element refers to the first element that is larger than the current one, starting from the current index and moving towards the end of the array, rather than searching for the largest element in the entire array.

Suggested Answer

Take a look at the array: 4, 5, 2, 25. For the first element '4', the next greater element is '5'. For '5', there is no greater element that follows, so we print '-1'. For '2', the next greater element is '25'. Lastly, for '25', there is no subsequent greater element, so we print '-1'. Thus, the output will be: 5, -1, 25, -1.

Alternative Answer

Take the array: 13, 7, 6, 12. For the first element '13', there is no subsequent greater element, so we output '-1'. For '7', the next greater element is '12'. For '6', the next greater element is also '12'. Lastly, for '12', there is no next greater element, hence we print '-1'. Therefore, the final output will be: -1, 12, 12, -1.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Amazon

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.