|
| 1 | +package com.thealgorithms.datastructures.stacks; |
| 2 | +import java.util.Arrays; |
| 3 | +import java.util.Stack; |
| 4 | + |
| 5 | + |
| 6 | +/* |
| 7 | + Given an array "input" you need to print the first smaller element for each element to the left side of an array. |
| 8 | + For a given element x of an array, the Next Smaller element of that element is the |
| 9 | + first smaller element to the left side of it. If no such element is present print -1. |
| 10 | + |
| 11 | + Example |
| 12 | + input = { 2, 7, 3, 5, 4, 6, 8 }; |
| 13 | + At i = 0 |
| 14 | + No elements to left of it : -1 |
| 15 | + At i = 1 |
| 16 | + Next smaller element between (0 , 0) is 2 |
| 17 | + At i = 2 |
| 18 | + Next smaller element between (0 , 1) is 2 |
| 19 | + At i = 3 |
| 20 | + Next smaller element between (0 , 2) is 3 |
| 21 | + At i = 4 |
| 22 | + Next smaller element between (0 , 3) is 4 |
| 23 | + At i = 5 |
| 24 | + Next smaller element between (0 , 4) is 3 |
| 25 | + At i = 6 |
| 26 | + Next smaller element between (0 , 5) is 6 |
| 27 | + |
| 28 | + result : [-1, 2, 2, 3, 3, 4, 6] |
| 29 | + |
| 30 | + 1) Create a new empty stack st |
| 31 | + |
| 32 | + 2) Iterate over array "input" , where "i" goes from 0 to input.length -1. |
| 33 | + a) We are looking for value just smaller than `input[i]`. So keep popping from "stack" |
| 34 | + till elements in "stack.peek() >= input[i]" or stack becomes empty. |
| 35 | + b) If the stack is non-empty, then the top element is our previous element. Else the previous element does not exist. |
| 36 | + c) push input[i] in stack. |
| 37 | + 3) If elements are left then their answer is -1 |
| 38 | + */ |
| 39 | + |
| 40 | +public class NextSmallerElement { |
| 41 | + public static int[] findNextSmallerElements(int[] array) |
| 42 | + { |
| 43 | + // base case |
| 44 | + if (array == null) { |
| 45 | + return array; |
| 46 | + } |
| 47 | + Stack<Integer> stack = new Stack<>(); |
| 48 | + int[] result = new int[array.length]; |
| 49 | + Arrays.fill(result, -1); |
| 50 | + |
| 51 | + for (int i = 0; i < array.length; i++) { |
| 52 | + while (!stack.empty() && stack.peek() >= array[i]) stack.pop(); |
| 53 | + if (stack.empty()) { |
| 54 | + result[i] = -1; |
| 55 | + } else { |
| 56 | + result[i] = stack.peek(); |
| 57 | + } |
| 58 | + stack.push(array[i]); |
| 59 | + } |
| 60 | + return result; |
| 61 | + } |
| 62 | + |
| 63 | + public static void main(String[] args) |
| 64 | + { |
| 65 | + int[] input = { 2, 7, 3, 5, 4, 6, 8 }; |
| 66 | + int[] result = findNextSmallerElements(input); |
| 67 | + System.out.println(Arrays.toString(result)); |
| 68 | + } |
| 69 | +} |
0 commit comments