![]() |
VOOZH | about |
Given an array arr[] of integers, find the Next Smaller Element (NSE) for each element in the array.
Examples:
Input: arr[] = [4, 8, 5, 2, 25]
Output: [2, 5, 2, -1, -1]
Explanation:
The first element smaller than 4 having index > 0 is 2.
The first element smaller than 8 having index > 1 is 5.
The first element smaller than 5 having index > 2 is 2.
There are no elements smaller than 2 having index > 3.
There are no elements smaller than 25 having index > 4.Input: arr[] = [13, 7, 6, 12]
Output: [7, 6, -1, -1]
Explanation:
The first element smaller than 13 having index > 0 is 7.
The first element smaller than 7 having index > 1 is 6.
There are no elements smaller than 6 having index > 2.
There are no elements smaller than 12 having index > 3.
Table of Content
The idea is to check the next smaller element for every element using a nested loop. For each element, we look at all elements to its right until we find a smaller one. If no such element exists, we store -1.
2 5 2 -1 -1
The idea is to use a monotonic increasing stack to find the next smaller element. We traverse the array from right to left. For each element, we remove all elements from the stack that are greater than or equal to it, since they cannot be the next smaller element. If the stack is not empty after this, the top element of the stack becomes the next smaller element for the current element. We then push the current element onto the stack.
2 5 2 -1 -1