Stacks and Queues Monotonic stack
220. Next Smaller Element
You are given an array of integers nums. For each position i, look at the values after it, from left to
right.
The next smaller element of nums[i] is the first of those values that is less than nums[i]. An equal
value is not smaller. If no value after position i is smaller, the answer is -1.
Return an array answer of the same length as nums, where answer[i] is the next smaller element of
nums[i]. Each answer is a value from nums, not its position.
Example 1
Input: nums = [6, 9, 4, 7, 7, 2, 8]
[4,4,2,2,2,-1,-1]Explanation: For both 6 and 9, the first smaller value after them is 4, and for 4 it is 2. The first 7 is followed by another 7, which is equal and not smaller, so both 7s get 2. Nothing after 2 or after 8 is smaller, so both get −1.
Example 2
Input: nums = [3, 0, 3, 3, 1]
[0,-1,1,1,-1]Explanation: 0 can be an answer: the first 3 is followed straight away by 0. No value is smaller than 0, so it gets −1. The 3 at index 2 skips the equal 3 after it, so both of the last two 3s get 1.
Example 3
Input: nums = [1, 4, 10, 25]
[-1,-1,-1,-1]Explanation: The values only rise, so no value has a smaller one after it.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 1050 ≤ nums[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.