package com.thealgorithms.stacks; import java.util.Arrays; import java.util.Stack; /** * Utility class to find the next smaller element for each element in a given integer array. * *
The next smaller element for an element x is the first smaller element on the left side of x in the array. * If no such element exists, the result will contain -1 for that position.
* *Example:
*
* Input: {2, 7, 3, 5, 4, 6, 8}
* Output: [-1, 2, 2, 3, 3, 4, 6]
*
*/
public final class NextSmallerElement {
private NextSmallerElement() {
}
/**
* Finds the next smaller element for each element in the given array.
*
* @param array the input array of integers
* @return an array where each element is replaced by the next smaller element on the left side in the input array,
* or -1 if there is no smaller element.
* @throws IllegalArgumentException if the input array is null
*/
public static int[] findNextSmallerElements(int[] array) {
if (array == null) {
throw new IllegalArgumentException("Input array cannot be null");
}
int[] result = new int[array.length];
Stack