|
| 1 | +package com.thealgorithms.datastructures.stacks; |
| 2 | + |
| 3 | +import java.util.Stack; |
| 4 | +import java.util.Arrays; |
| 5 | + |
| 6 | +public final class NearestElement { |
| 7 | + |
| 8 | + private NearestElement() {} |
| 9 | + |
| 10 | + public static int[] nearestGreaterToRight(int[] arr) { |
| 11 | + int n = arr.length; |
| 12 | + int[] result = new int[n]; |
| 13 | + Stack<Integer> indexStack = new Stack<>(); |
| 14 | + for (int i = n - 1; i >= 0; i--) { |
| 15 | + while (!indexStack.isEmpty() && arr[i] >= arr[indexStack.peek()]) { |
| 16 | + indexStack.pop(); |
| 17 | + } |
| 18 | + result[i] = indexStack.isEmpty() ? -1 : arr[indexStack.peek()]; |
| 19 | + indexStack.push(i); |
| 20 | + } |
| 21 | + return result; |
| 22 | + } |
| 23 | + |
| 24 | + public static int[] nearestGreaterToLeft(int[] arr) { |
| 25 | + int n = arr.length; |
| 26 | + int[] result = new int[n]; |
| 27 | + Stack<Integer> indexStack = new Stack<>(); |
| 28 | + for (int i = 0; i < n; i++) { |
| 29 | + while (!indexStack.isEmpty() && arr[i] >= arr[indexStack.peek()]) { |
| 30 | + indexStack.pop(); |
| 31 | + } |
| 32 | + result[i] = indexStack.isEmpty() ? -1 : arr[indexStack.peek()]; |
| 33 | + indexStack.push(i); |
| 34 | + } |
| 35 | + return result; |
| 36 | + } |
| 37 | + |
| 38 | + public static int[] nearestSmallerToRight(int[] arr) { |
| 39 | + int n = arr.length; |
| 40 | + int[] result = new int[n]; |
| 41 | + Stack<Integer> indexStack = new Stack<>(); |
| 42 | + for (int i = n - 1; i >= 0; i--) { |
| 43 | + while (!indexStack.isEmpty() && arr[i] <= arr[indexStack.peek()]) { |
| 44 | + indexStack.pop(); |
| 45 | + } |
| 46 | + result[i] = indexStack.isEmpty() ? -1 : arr[indexStack.peek()]; |
| 47 | + indexStack.push(i); |
| 48 | + } |
| 49 | + return result; |
| 50 | + } |
| 51 | + |
| 52 | + public static int[] nearestSmallerToLeft(int[] arr) { |
| 53 | + int n = arr.length; |
| 54 | + int[] result = new int[n]; |
| 55 | + Stack<Integer> indexStack = new Stack<>(); |
| 56 | + for (int i = 0; i < n; i++) { |
| 57 | + while (!indexStack.isEmpty() && arr[i] <= arr[indexStack.peek()]) { |
| 58 | + indexStack.pop(); |
| 59 | + } |
| 60 | + result[i] = indexStack.isEmpty() ? -1 : arr[indexStack.peek()]; |
| 61 | + indexStack.push(i); |
| 62 | + } |
| 63 | + return result; |
| 64 | + } |
| 65 | + |
| 66 | + public static void main(String[] args) { |
| 67 | + int[] sampleArray = {4, 5, 2, 10, 8}; |
| 68 | + System.out.println("Nearest Greater to Right: " + Arrays.toString(nearestGreaterToRight(sampleArray))); |
| 69 | + System.out.println("Nearest Greater to Left: " + Arrays.toString(nearestGreaterToLeft(sampleArray))); |
| 70 | + System.out.println("Nearest Smaller to Right: " + Arrays.toString(nearestSmallerToRight(sampleArray))); |
| 71 | + System.out.println("Nearest Smaller to Left: " + Arrays.toString(nearestSmallerToLeft(sampleArray))); |
| 72 | + } |
| 73 | +} |
0 commit comments