File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
src/main/java/org/Stacks/practice Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ package org .Stacks .practice ;
2
+ import java .util .ArrayList ;
3
+ import java .util .Stack ;
4
+
5
+ /**
6
+ * @author hemant
7
+ *
8
+ * Given an array A, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i.
9
+ *
10
+ * More formally,
11
+ *
12
+ * G[i] for an element A[i] = an element A[j] such that
13
+ *
14
+ * j is maximum possible AND
15
+ *
16
+ * j < i AND
17
+ *
18
+ * A[j] < A[i]
19
+ *
20
+ * Elements for which no smaller element exist, consider next smaller element as -1.
21
+ */
22
+ public class NearestSmallestElement {
23
+ public ArrayList <Integer > prevSmaller (ArrayList <Integer > A ){
24
+ ArrayList <Integer > res =new ArrayList <>();
25
+ Stack <Integer > stack1 =new Stack <>();
26
+
27
+ for (Integer integer : A ) {
28
+ while (!stack1 .isEmpty () && stack1 .peek () >= integer ) {
29
+ stack1 .pop ();
30
+ }
31
+ if (!stack1 .isEmpty ()) {
32
+ res .add (stack1 .peek ());
33
+ } else {
34
+ res .add (-1 );
35
+ }
36
+ stack1 .add (integer );
37
+
38
+
39
+ }
40
+ return res ;
41
+ }
42
+
43
+ }
You can’t perform that action at this time.
0 commit comments