Skip to content

Commit 47688da

Browse files
authored
Create Next Smallest to Right.java
1 parent 7966fb7 commit 47688da

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
//Problem Statement :: https://practice.geeksforgeeks.org/problems/help-classmates--141631/1?utm_source=gfg&utm_medium=article&utm_campaign=bottom_sticky_on_article
2+
3+
class Solution {
4+
public static int[] help_classmate(int arr[], int n)
5+
{
6+
// Your code goes here
7+
//Lets Play with Stack::: why stack ::
8+
// broute force ::
9+
// for(int i=0;i<n;i++){
10+
// for(int j=i-1;j>=0;j--){} --since j is dependent on i -------think of stack:::
11+
//}
12+
13+
int[] res = new int[arr.length];
14+
Stack<Integer> st = new Stack<>();
15+
for(int i=n-1;i>=0;i--){
16+
if(st.isEmpty()){
17+
res[i] =-1;
18+
}else if(st.peek()<arr[i]){
19+
res[i] =st.peek();
20+
}else{
21+
while(!st.isEmpty() && st.peek()>=arr[i]){
22+
st.pop();
23+
}
24+
if(st.isEmpty()){
25+
res[i] =-1;
26+
}else{
27+
res[i] =st.peek();
28+
}
29+
}
30+
st.push(arr[i]);
31+
}
32+
return res;
33+
}
34+
}

0 commit comments

Comments
 (0)