|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +public class MonotonicStack { |
| 4 | + |
| 5 | + // Returns Next Greater Element for each element in the array |
| 6 | + public static int[] nextGreaterElement(int[] arr) { |
| 7 | + int n = arr.length; |
| 8 | + int[] result = new int[n]; |
| 9 | + Stack<Integer> stack = new Stack<>(); // stores indices |
| 10 | + |
| 11 | + for (int i = n - 1; i >= 0; i--) { |
| 12 | + // Pop elements smaller or equal to arr[i] |
| 13 | + while (!stack.isEmpty() && arr[i] >= arr[stack.peek()]) { |
| 14 | + stack.pop(); |
| 15 | + } |
| 16 | + |
| 17 | + // If stack is empty, no greater element to the right |
| 18 | + result[i] = stack.isEmpty() ? -1 : arr[stack.peek()]; |
| 19 | + |
| 20 | + // Push current index onto stack |
| 21 | + stack.push(i); |
| 22 | + } |
| 23 | + |
| 24 | + return result; |
| 25 | + } |
| 26 | + |
| 27 | + // Returns Next Smaller Element for each element in the array |
| 28 | + public static int[] nextSmallerElement(int[] arr) { |
| 29 | + int n = arr.length; |
| 30 | + int[] result = new int[n]; |
| 31 | + Stack<Integer> stack = new Stack<>(); // stores indices |
| 32 | + |
| 33 | + for (int i = n - 1; i >= 0; i--) { |
| 34 | + // Pop elements greater or equal to arr[i] |
| 35 | + while (!stack.isEmpty() && arr[i] <= arr[stack.peek()]) { |
| 36 | + stack.pop(); |
| 37 | + } |
| 38 | + |
| 39 | + result[i] = stack.isEmpty() ? -1 : arr[stack.peek()]; |
| 40 | + stack.push(i); |
| 41 | + } |
| 42 | + |
| 43 | + return result; |
| 44 | + } |
| 45 | + |
| 46 | + public static void main(String[] args) { |
| 47 | + int[] arr = {4, 5, 2, 10, 8}; |
| 48 | + |
| 49 | + int[] nextGreater = nextGreaterElement(arr); |
| 50 | + int[] nextSmaller = nextSmallerElement(arr); |
| 51 | + |
| 52 | + System.out.println("Next Greater Element: " + Arrays.toString(nextGreater)); |
| 53 | + System.out.println("Next Smaller Element: " + Arrays.toString(nextSmaller)); |
| 54 | + } |
| 55 | +} |
0 commit comments