File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments