GeeksforGeeks Medium

Next Smaller Element

Next Smaller Element is a GFG problem (Medium). For every element of arr, return the first element to its right that is strictly smaller. If no such element exists, return −1 for that position.

  • Only a strictly smaller value counts. An equal value is not an answer.
  • With up to 10⁵ elements, comparing each element with everything to its right can take about 5 × 10⁹ steps, so a linear pass is needed.
Constraints
  • 1 <= arr.size() <= 10⁵
  • 1 <= arr[i] <= 10⁵
stackmonotonic-stack
Open on GeeksforGeeks ↗
02

Intuition

Read the array from the right end. Not every element to the right of arr[i] can be an answer for something. Once a value v sits in front of a larger-or-equal value w, nobody to the left of v can ever pick w: they reach v first, and v is no larger.

So keep a stack of the values that can still be an answer, nearest on top. Scanning right to left, the current value removes every candidate that is not smaller than it, because it now blocks them. Whatever is left on top is the nearest smaller value. Then the current value joins the stack as the newest candidate.

How to spot this pattern

"First smaller value to the right (or left)" for every element is the monotonic stack pattern. It appears inside harder problems as the step that finds how far each element's range reaches.

03

Approach

Try it first

Before reading on, take an element v and a larger value w somewhere to its right. Can anything to the left of v have w as its next smaller element? Use the answer to decide which values are worth remembering. Aim for O(n).

1

Start from the right end

Fill res with −1 and walk i from n − 1 down to 0 with an empty stack. The stack holds values to the right of i that may still be the next smaller element of arr[i] or of something further left.

2

Pop candidates that are not smaller

While the top of the stack is ≥ arr[i], pop it. It cannot answer arr[i], and it cannot answer anything further left either, because arr[i] stands in front of it and is no larger.

3

The top is the answer

If the stack still has a value, it is smaller than arr[i] and it is the nearest value that survived, so it goes into res[i]. An empty stack means nothing to the right is smaller, and −1 stays.

4

Push the current value

Push arr[i]. It is now the nearest candidate for every element to its left. After the pops, the values on the stack strictly increase from bottom to top.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def nextSmallerEle(self, arr):
▶3 n = len(arr)
▶4 res = [-1] * n
▶5 stack = []
▶6 for i in range(n - 1, -1, -1):
▶7 while stack and stack[-1] >= arr[i]:
▶8 stack.pop()
▶9 if stack:
▶10 res[i] = stack[-1]
▶11 stack.append(arr[i])
▶12 return res
scan right to left4#08#15#22#325#4stackanswerstart at the right end
n5
Every answer starts as −1 and the stack of candidates is empty. Going from the right means that when we reach an element, everything to its right has already been seen.
scan right to left4#08#15#22#325#4stack25← topanswer−1nothing smaller → −1, 25 becomes a candidate
i4
stack size1
The stack is empty, so no value to the right of 25 is smaller and its answer stays −1. 25 goes on top. It is now the nearest candidate for everything to its left.
scan right to left4#08#15#22#325#4stackanswer−125 is not smaller than 2 → drop it
i3
arr[i]2
dropped25
The candidate 25 is larger than 2. It cannot answer 2, and anything further left will meet 2 before it, so 25 can never be an answer again.
scan right to left4#08#15#22#325#4stack2← topanswer−1−1nothing smaller → −1, 2 becomes a candidate
i3
stack size1
The stack is empty, so no value to the right of 2 is smaller and its answer stays −1. 2 goes on top. It is now the nearest candidate for everything to its left.
scan right to left4#08#15#22#325#4stack2← topanswer2−1−1next smaller of 5 is 2
i2
answer2
After the clean-up the top of the stack, 2 at #3, is smaller than 5. It is also the nearest one still standing, so it is the answer.
scan right to left4#08#15#22#325#4stack25← topanswer2−1−15 becomes a candidate
i2
stack size2
5 goes on top. It is now the nearest candidate for everything to its left.
scan right to left4#08#15#22#325#4stack25← topanswer52−1−1next smaller of 8 is 5
i1
answer5
After the clean-up the top of the stack, 5 at #2, is smaller than 8. It is also the nearest one still standing, so it is the answer.
scan right to left4#08#15#22#325#4stack258← topanswer52−1−18 becomes a candidate
i1
stack size3
8 goes on top. It is now the nearest candidate for everything to its left.
scan right to left4#08#15#22#325#4stack25← topanswer52−1−18 is not smaller than 4 → drop it
i0
arr[i]4
dropped8
The candidate 8 is larger than 4. It cannot answer 4, and anything further left will meet 4 before it, so 8 can never be an answer again.
scan right to left4#08#15#22#325#4stack2← topanswer52−1−15 is not smaller than 4 → drop it
i0
arr[i]4
dropped5
The candidate 5 is larger than 4. It cannot answer 4, and anything further left will meet 4 before it, so 5 can never be an answer again.
scan right to left4#08#15#22#325#4stack2← topanswer252−1−1next smaller of 4 is 2
i0
answer2
After the clean-up the top of the stack, 2 at #3, is smaller than 4. It is also the nearest one still standing, so it is the answer.
scan right to left4#08#15#22#325#4stack24← topanswer252−1−14 becomes a candidate
i0
stack size2
4 goes on top. It is now the nearest candidate for everything to its left.
scan right to left4#08#15#22#325#4stack24← topanswer252−1−1done: 2, 5, 2, -1, -1
return2, 5, 2, -1, -1
Each value went on the stack once and came off at most once, so the whole scan took a single pass.
05

Common pitfalls

Keeping equal values on the stack

✗ Wrong
while stack and stack[-1] > arr[i]:
✓ Right
while stack and stack[-1] >= arr[i]:

With >, an equal value survives and becomes the answer. For arr = [5, 5, 3] the first 5 would get 5, but 5 is not smaller than 5. The correct output is [3, 3, -1].

Reading the top before popping

✗ Wrong
if stack:
    res[i] = stack[-1]
while stack and stack[-1] >= arr[i]:
    stack.pop()
✓ Right
while stack and stack[-1] >= arr[i]:
    stack.pop()
if stack:
    res[i] = stack[-1]

The top may be larger than arr[i] until the pops run. For arr = [1, 3] the 1 would read 3 as its answer, but 3 is not smaller; the output should be [-1, -1].

06

Edge cases

A strictly decreasing array, like [5, 4, 3, 2]

Nothing is ever popped, so every value stays on the stack and it grows to n entries. Each answer is simply the next element, and the last is −1.

07

Complexity

Time
O(n)
Space
O(n)
Each value is pushed once and popped at most once, so the inner loop does at most n pops over the whole run. The stack can hold all n values, as in a strictly decreasing array.
08

Next Smaller Element FAQ

How do I return the index of the next smaller element instead of its value?

Push indices instead of values and compare arr[stack[-1]]. Store the index in res. Indices are what range problems need, because they tell you how far an element's run extends.

Where does this come up in harder problems?

In Largest Rectangle in Histogram and Sum of Subarray Minimums, each bar's range ends at its previous and next smaller elements, so both are found with this stack.

Can I scan from left to right instead?

Yes. Keep indices that have no answer yet, and when a smaller value arrives, pop each larger one and give it that value. The next greater element page runs that direction with the comparison flipped.