|
| 1 | + |
| 2 | + |
| 3 | +Problem Set: |
| 4 | + |
| 5 | + 1. Nearest Greater Element to Left. |
| 6 | + 2. Nearest Greater Element to Right. ( Next Largest Element) -> Important |
| 7 | + 3. Nearest Smaller to Left. |
| 8 | + 4. Nearest Smaller to Right. |
| 9 | + |
| 10 | + |
| 11 | + So, Basically all of these are Problems are similar with minor Variations. |
| 12 | + |
| 13 | + 1. Nearest Greater Element to Left : Here we have to find the next Immediate Greater element to the Left Side. |
| 14 | + |
| 15 | + Ex : N = 8, arr[] = {10, 3, 0, 1, 15, 0, 2, 4} |
| 16 | + |
| 17 | + o/p : {-1, 10, 3, 3, -1, 15, 15, 15 } |
| 18 | + |
| 19 | + Approach 1 --> This can be solved in O(n^2) time complexity by running 2 for Loop, where for each element we will run the loop to sear ch the nearest greater element on the left side. |
| 20 | + |
| 21 | + // Code |
| 22 | + public static int[] nextGreaterToLeft(int[] arr, int size) { |
| 23 | + int[] ngl = new int[size]; |
| 24 | + for (int i = 0; i < size; i++) { |
| 25 | + int max = -1; |
| 26 | + for (int j = i-1; j >= 0; j--) { |
| 27 | + if (arr[j] > arr[i]) { |
| 28 | + max = arr[j]; |
| 29 | + break; |
| 30 | + } |
| 31 | + } |
| 32 | + ngl[i] = max; |
| 33 | + } |
| 34 | + return ngl; |
| 35 | + } |
| 36 | + |
| 37 | + Time Complexity : O(N ^ 2) |
| 38 | + Space Complexity : O(N) |
| 39 | + |
| 40 | + Approach 2 --> By using Stack |
| 41 | + i. if stack is empty , -1 |
| 42 | + ii. keep poping the elements which are smaller than the current element. |
| 43 | + iii. print top element of stack if stack not empty else print -1. |
| 44 | + |
| 45 | + //Code |
| 46 | + |
| 47 | + public int[] nextGreaterToLeft(int[] arr, int size) { |
| 48 | + int[] ngl = new int[size]; |
| 49 | + Stack<Integer> stack = new Stack<>(); |
| 50 | + for (int i = 0; i < size; i++) { |
| 51 | + if (!stack.isEmpty()) { |
| 52 | + while(!stack.isEmpty() && stack.peek() <= arr[i]) { |
| 53 | + stack.pop(); |
| 54 | + } |
| 55 | + } |
| 56 | + ngl[i] = stack.isEmpty() ? -1 : stack.peek(); |
| 57 | + stack.push(arr[i]); |
| 58 | + } |
| 59 | + return ngl; |
| 60 | + } |
| 61 | + |
| 62 | + Time Complexity : o(N) |
| 63 | + |
| 64 | + 2. Nearest Greater Element to Right |
| 65 | + |
| 66 | + Approach 1 --> Applying the Brute Force. |
| 67 | + |
| 68 | + Time Complexity --> O( N ^ 2) |
| 69 | + |
| 70 | + |
| 71 | + |
0 commit comments