Find the Previous Smallest Element Using Stack

package org.wesome.dsalgo;

import java.util.Stack;
import java.util.stream.IntStream;

public class PreviousSmallestElement {
    public static int[] previousSmallestElement(int[] arr) {
        if (arr == null || arr.length == 0) {
            return new int[0];
        }
        Stack<Integer> stack = new Stack<>();
        int previousSmallestElementArray[] = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            /*  if stack is not empty and stack top is smaller than array item, put it as previousSmallestElementArray    */
            while (!stack.empty()) {
                if (arr[i] > stack.peek()) {
                    previousSmallestElementArray[i] = stack.peek();
                    break;
                } /*    other wise keep popping element   */ else {
                    stack.pop();
                }
            }
            /*  if stack is empty, means there was no element greater than current array element, so put -1   */
            if (stack.empty()) {
                previousSmallestElementArray[i] = -1;
            }
            stack.push(arr[i]);
        }
        IntStream.range(0, arr.length).mapToObj(i -> arr[i] + " --> " + previousSmallestElementArray[i]).forEach(System.out::println);
        return previousSmallestElementArray;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class PreviousSmallestElementTest {
    @Test
    void previousSmallestElementTest1() {
        int[] arr = new int[]{2, 5, 3, 7, 8, 1, 9};
        int[] result = new int[]{-1, 2, 2, 3, 7, -1, 1};
        Assertions.assertArrayEquals(result, PreviousSmallestElement.previousSmallestElement(arr));
    }

    @Test
    void previousSmallestElementTest2() {
        int[] arr = new int[]{1, 2, 3, 4, 5};
        int[] result = new int[]{-1, 1, 2, 3, 4};
        Assertions.assertArrayEquals(result, PreviousSmallestElement.previousSmallestElement(arr));
    }

    @Test
    void previousSmallestElementTest3() {
        int[] arr = new int[]{5, 4, 3, 2, 1};
        int[] result = new int[]{-1, -1, -1, -1, -1};
        Assertions.assertArrayEquals(result, PreviousSmallestElement.previousSmallestElement(arr));
    }

    @Test
    void previousSmallestElementTest4() {
        int[] arr = new int[]{-1, -2, -3, -4, -5};
        int[] result = new int[]{-1, -1, -1, -1, -1};
        Assertions.assertArrayEquals(result, PreviousSmallestElement.previousSmallestElement(arr));
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.4.1"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on