1+ package stack_and_queue ;
2+ import java .util .*;
3+ import java .util .Stack ;
4+ import java .lang .*;
5+
6+ // Problem Title => Next Smaller Element
7+ public class P38 {
8+
9+ // prints element and NSE pair for all elements of arr[] of size n
10+ public static void printNSE (int [] arr , int n ){
11+ Stack <Integer > s = new Stack <>();
12+
13+ // push the first element to stack
14+ s .push (arr [0 ]);
15+
16+ // iterate for rest of the elements
17+ for (int i = 1 ; i < n ; i ++){
18+ if (s .empty ()){
19+ s .push (arr [i ]);
20+ continue ;
21+ }
22+
23+ // if stack is not empty,
24+ // then pop an element from stack.
25+ // If the popped element is greater than next, then
26+ // (a) print the pair,
27+ // (b) keep popping while elements are greater and stack is not empty.
28+ while (!s .empty () && s .peek () > arr [i ]){
29+ System .out .println (s .peek () + " --> " + arr [i ]);
30+ s .pop ();
31+ }
32+
33+ // push next to stack so that we can find next smaller for it
34+ s .push (arr [i ]);
35+ }
36+
37+ // After iterating over the loop,
38+ // the remaining elements in stack do not have the next smaller element,
39+ // so print -1 for them
40+ while (!s .empty ()){
41+ System .out .println (s .peek () + " --> " + "-1" );
42+ s .pop ();
43+ }
44+ }
45+
46+ // Driver function
47+ public static void main (String [] args ) {
48+ // Scanner object for input
49+ Scanner sc = new Scanner (System .in );
50+
51+ // Taking Size of the array as input from user
52+ int n = sc .nextInt ();
53+
54+ // Taking the elements of array as input from user
55+ int [] arr = new int [n ];
56+ for (int i = 0 ; i < n ; i ++)
57+ arr [i ] = sc .nextInt ();
58+
59+ // Printing the Next Smaller Element by calling printNSE method
60+ printNSE (arr , n );
61+ }
62+ }
0 commit comments