Next Smaller Element
Created on: Jan 28, 2025
Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].
Input: [4, 8, 5, 2, 25] Output: [2, 5, 2, -1, -1] Input: [13, 7, 6, 12] Output: [7, 6, -1, -1]
import java.util.Stack; public class Solution { public static int[] countSmaller(int[] nums) { return null; } public static void main(String[] args) { int[] arr = {4, 8, 5, 2, 25}; int[] nextSmaller = countSmaller(arr); for (int i = 0; i < nextSmaller.length; i++) { System.out.print(nextSmaller[i] + " "); } } }
public static int[] countSmaller(int[] nums) { int[] res = new int[nums.length]; Stack<Integer> stack = new Stack<>(); for (int i = nums.length - 1; i >= 0; i--) { while (!stack.isEmpty() && stack.peek() >= nums[i]) { stack.pop(); } if (stack.isEmpty()) { res[i] = -1; } else { res[i] = stack.peek(); } stack.push(nums[i]); } return res; }
2 5 2 -1 -1 Process finished with exit code 0
