Next Greater Element Problem Statement

You are provided with an array or list ARR containing N positive integers. Your task is to determine the Next Greater Element (NGE) for each element in the array.

The Next Greater Element for an element X is the first element on the right side of X in the array ARR that is greater than X. If no such element exists, return -1.

Example:

Input:
ARR = [7, 12, 1, 20]
Output:
[12, 20, 20, -1]
Explanation:

The next greater element for 7 is 12, for 12 it is 20, for 1 it is 20, and for 20 there is no greater element to the right, so it is -1.

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 5 * 10^3
  • 1 <= ARR[i] <= 10^9
  • Time Limit: 1 sec
Note:

You are not required to print anything; it has already been taken care of. Just implement the function.

AnswerBot
1y

The task is to find the next greater element for each element in an array.

  • Iterate through the array from right to left

  • Use a stack to keep track of the elements

  • For each element, pop elements from the s...read more

Help your peers!
Add answer anonymously...
Tata 1mg Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter