forked from architsingla13/InterviewBit-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNearestSmaller.java
More file actions
40 lines (32 loc) · 761 Bytes
/
NearestSmaller.java
File metadata and controls
40 lines (32 loc) · 761 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package Stacks;
import java.util.ArrayList;
import java.util.Stack;
/**
* Author - archit.s
* Date - 24/10/18
* Time - 11:47 PM
*/
public class NearestSmaller {
public ArrayList<Integer> prevSmaller(ArrayList<Integer> A) {
ArrayList<Integer> r = new ArrayList<>();
if(A.size()==0){
return r;
}
r.add(-1);
Stack<Integer> s = new Stack<>();
s.push(A.get(0));
for(int i=1;i<A.size();i++){
while(!s.empty() && s.peek()>=A.get(i)){
s.pop();
}
if(s.empty()){
r.add(-1);
}
else{
r.add(s.peek());
}
s.push(A.get(i));
}
return r;
}
}