-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNSR.java
More file actions
54 lines (35 loc) · 1.44 KB
/
Copy pathNSR.java
File metadata and controls
54 lines (35 loc) · 1.44 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Nearest Smallest to the Right or next smallest number to the right
// Youtube : https://www.youtube.com/watch?v=nc1AYFyvOR4&list=PL_z_8CaSLPWdeOezg68SKkeLN4-T_jNHd&index=6
//TC = O(n)
import java.io.*;
import java.util.*;
public class NSR{
public static List<Integer> getTheNearestSmallestNumberToTheRight(int[] a){
List<Integer> res = new ArrayList<>();
Stack<Integer> s = new Stack<Integer>();
for(int i =a.length-1;i>=0;i--){
//Check if stack is empty
if(s.size() == 0){
res.add(0,-1);
}else if(s.size() > 0 && s.peek() < a[i]){
res.add(0,s.peek());
}else if (s.size() > 0 && s.peek() >= a[i]){
while(s.size() > 0 && s.peek() >= a[i]){
s.pop();
}
if(s.size() == 0){
res.add(0,-1);
}else{
res.add(0,s.peek());
}
}
s.push(a[i]);
}
return res;
}
public static void main(String[] args){
int[] a = {2 , 3 , 0, 5};
System.out.println("The nearest smallest number to the right is "+ getTheNearestSmallestNumberToTheRight(a));
}
}
//o/p:- The nearest smallest number to the right is [0, 0, -1, -1]