Next Greater Element

You are given an array arr of length N. You have to return a list of integers containing the NGE(next greater element) of each element of the given array. The NGE for an element X is the first greater element on the right side of X in the array. Elements for which no greater element exists, consider the NGE as -1.

For Example :

If the given array is [1, 3, 2], then you need to return [3, -1, -1]. Because for 1, 3 is the next greater element, for 3 it does not have any greater number to its right, and similarly for 2.
Input Format :
The first line of input contains a single integer T, representing the number of test cases or queries to be run. 

Then the T test cases follow.

The first line of each test case contains an integer N, representing the length of the input array(ARR).

The second line contains N single space-separated integers representing elements of the array arr.
Output Format :
For each test case, print a list of integers each representing the NGE(next greater element) of each element of the given array in a single line.
Note :
You are not required to print the expected output, it has already been taken care of. Just implement the function.
Constraints :
1 <= T <= 10
1 <= N <= 10^5
0 <= ARR[i] <= 10^9

Time Limit: 1sec
AnswerBot
1y

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

  • Iterate through the array from right to left.

  • Use a stack to keep track of the next greater element.

  • Pop elements from th...read more

CodingNinjas
author
2y
Brute Force
  1. Initialise an array ans of length N to store the next greater number of arr[i] at index i.
  2. Traverse the given array and for every element at index I
    • Initialise a variable next to -1.
    • Run a loo...read more
CodingNinjas
author
2y
Optimal Approach
  1. Initialise an array ans of length N to store the next greater number of arr[i] at index i.
  2. Create a stack of type integer, where we will store the smaller element at the top.
  3. Traverse th...read more
incredibleblack
6mo
student at
National Institute of Technology (NIT), Tiruchirappalli
What is the error in this code? public class Main { public static void main(String[] args) { Scanner...read more
Hishaamudin Z
1y
t= int(input()) for _ in range(t): arr = list(map(int,input().split())) n = len(arr) res = [] curr = arr[0] for i in range(1,n): temp = -1 if (currread more
Add answer anonymously...
Sigmoid Data Engineer 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
Get AmbitionBox app

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