Skip to content

Commit 8948f24

Browse files
SmallestNearestElement
1 parent 9f6660e commit 8948f24

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
}

0 commit comments

Comments
 (0)