Next Greater Element

1 min read
class Solution {
public ArrayList nextLargerElement(int[] arr) {
int n = arr.length;
int[] result = new int[n];
Stack stack = new Stack<>();
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && stack.peek() <= arr[i]) {
stack.pop();
}
result[i] = stack.isEmpty() ? -1 : stack.peek();
stack.push(arr[i]);
}
// Convert array to ArrayList
ArrayList list = new ArrayList<>();
for (int val : result) { list.add(val);
}
return list;
}
}
0
Subscribe to my newsletter
Read articles from Mohd Shakeel directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
