Company: Snapdeal, Samsung, PayU, Informatica, CouponDunia, Amazon
Question:
Question:
Given an array A [ ] having distinct elements, the task is to find the next greater element for each element of the array in order of their appearance in the array. If no such element exists, output -1
Input:
The first line of input contains a single integer T denoting the number of test cases.Then T test cases follow. Each test case consists of two lines. The first line contains an integer N denoting the size of the array. The Second line of each test case contains N space separated positive integers denoting the values/elements in the array A[ ].
Output:
For each test case, print in a new line, the next greater element for each array element separated by space in order.
Constraints:
1<=T<=200
1<=N<=1000
1<=A[i]<=1000
Example:
Input
1
4
1 3 2 4
Output
3 4 4 -1
Explanation
In the array, the next larger element to 1 is 3 , 3 is 4 , 2 is 4 and for 4 ? since it doesn't exist hence -1.
The first line of input contains a single integer T denoting the number of test cases.Then T test cases follow. Each test case consists of two lines. The first line contains an integer N denoting the size of the array. The Second line of each test case contains N space separated positive integers denoting the values/elements in the array A[ ].
Output:
For each test case, print in a new line, the next greater element for each array element separated by space in order.
Constraints:
1<=T<=200
1<=N<=1000
1<=A[i]<=1000
Example:
Input
1
4
1 3 2 4
Output
3 4 4 -1
Explanation
In the array, the next larger element to 1 is 3 , 3 is 4 , 2 is 4 and for 4 ? since it doesn't exist hence -1.
CODE:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
int m = sc.nextInt();
for(int mi=0;mi<m;mi++){
int n = sc.nextInt();
int a[]= new int [n];
int res[]= new int[n];
for(int i1=0;i1<n;i1++){
a[i1]=sc.nextInt();
}
find(a,res,n);
System.out.println();
}
}
public static void find(int [] a,int []res, int n){
Stack <Integer> s= new Stack<>();
s.push(a[n-1]);
res[n-1]=-1;
for(int i=n-2;i>=0;i--){
while(!s.empty() && s.peek() < a[i]){
s.pop();}
if(s.empty()){res[i]=-1;}
else{
res[i]=s.peek();}
s.push(a[i]);
}
for(int j=0;j<n;j++){System.out.print(res[j]+" ");}
}
}
EXECUTION TIME: 0.14s
Comments
Post a Comment