-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextSmaller.java
More file actions
45 lines (34 loc) · 1.14 KB
/
NextSmaller.java
File metadata and controls
45 lines (34 loc) · 1.14 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
import java.util.ArrayList;
import java.util.Stack;
public class NextSmaller {
static ArrayList<Integer> nextSmallerElement(int[] arr) {
int n = arr.length;
ArrayList<Integer> result = new ArrayList<>(n);
// Initialize all results as -1
for (int i = 0; i < n; i++) result.add(-1);
Stack<Integer> st = new Stack<>();
// Traverse from right to left
for (int i = n - 1; i >= 0; i--) {
// Pop all greater or equal elements
while (!st.isEmpty() && st.peek() >= arr[i]) {
st.pop();
}
// If stack not empty → top is next smaller element
if (!st.isEmpty()) {
result.set(i, st.peek());
}
// Push current element
st.push(arr[i]);
}
return result;
}
public static void main(String[] args) {
int[] arr = {4, 8, 5, 2, 25};
ArrayList<Integer> nse = nextSmallerElement(arr);
System.out.println("Next Smaller Elements:");
for (int x : nse) {
System.out.print(x + " ");
}
System.out.println();
}
}