I/P: {1, 3, 4, 7, 2, 6, 8}
O/P: {3, 4, 7, 8, 6, 8, -1}
package pep.Day25;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Stack;
public class Next_Greater_Element_To_The_RIght {
public static void main(String[] args) {
int[] arr = new int[]{1, 3, 4, 7, 2, 6, 8};
int[] ans = solve(arr);
display(ans);
}
private static void display(int[] ans) {
for (int i : ans)
System.out.print(i + "\t");
System.out.println();
}
private static int[] solve(int[] arr) {
int n = arr.length;
Stack<Integer> stack = new Stack<>();
int[] ans = new int[n];
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && stack.peek() <= arr[i])
stack.pop();
ans[i] = stack.isEmpty() ? -1 : stack.peek();
stack.push(arr[i]);
}
return ans;
}
}
Time Complexity: O(n)
Space Complexity: O(n)
No comments:
Post a Comment