VOOZH about

URL: https://www.geeksforgeeks.org/dsa/next-smaller-element/

⇱ Next Smaller Element - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Next Smaller Element

Last Updated : 15 Sep, 2025

Given an array arr[] of integers, find the Next Smaller Element (NSE) for each element in the array.

  • The Next Smaller Element of an element x is defined as the first element to the right of x in the array that is strictly smaller than x.
  • If no such element exists for a particular position, the NSE should be considered as -1.

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.

[Naive Approach] Using Nested loops - O(n2) Time O(1) Space

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.


Output
2 5 2 -1 -1 

[Expected Approach] Using Monotonic Stack - O(n) Time O(n) Space

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.


Output
2 5 2 -1 -1 
Comment
Article Tags: