Skip to content

Commit 7966fb7

Browse files
authored
Create Next Greater to Left.java
1 parent b373360 commit 7966fb7

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
//Problem Statement : Nearest Greater to Left::
2+
//IP :: 1,3,2,4
3+
//OP :: -1,-1,3,-1
4+
//Lets Play with Stack::
5+
6+
import java.util.*;
7+
public class Main
8+
{
9+
public static void main(String[] args) {
10+
int arr[] = new int[]{5,3,2,4,3,6,8,2};
11+
int res[] =nextGreaterLeft(arr);
12+
for(int i=0;i<arr.length;i++){
13+
System.out.print(res[i]+" ");
14+
}
15+
}
16+
public static int[] nextGreaterLeft(int[] arr){
17+
Stack<Integer> st = new Stack<>();
18+
int res[] = new int[arr.length];
19+
20+
for(int i=0;i<arr.length;i++){
21+
if(st.isEmpty()){
22+
res[i]=-1;
23+
}else if(st.peek()>arr[i]){
24+
res[i]=st.peek();
25+
}else{
26+
while(!st.isEmpty() && st.peek()<=arr[i]){
27+
st.pop();
28+
}
29+
if(st.isEmpty()){
30+
res[i] =-1;
31+
}else{
32+
res[i] =st.peek();
33+
}
34+
}
35+
st.push(arr[i]);
36+
}
37+
return res;
38+
}
39+
}

0 commit comments

Comments
 (0)