Next Smaller Element

Pattern: Monotonic stack

medium

Walk from the right with a stack of candidates. Pop everything not smaller than the current value, since nothing further left can use them either. The top that remains is the answer, then push the current value.

The problem

For each value, return the first strictly smaller value to its right, or -1. [4, 8, 5, 2, 25] gives [2, 5, 2, -1, -1].

Think first

  • Scanning from the right, which values are worth remembering?
  • When the current value is smaller than a remembered one, is that one still useful?
  • What is on top after popping?

Hints

    Brute force, and why it fails

    For each index, scan right until a smaller value: O(n²).

    The key insight

    From the right, the useful candidates increase from bottom to top. Popping those that are not smaller leaves the answer on top.

    Dry run

    40 
    81 
    52 
    23 
    254i
    stack25

    arr = [4, 8, 5, 2, 25]. From the right: 25 has nothing, -1. Push 25.

    Step 1 of 4

    The plan

    for i from n - 1 down to 0:
        while stack and top >= arr[i]: pop
        out[i] = top if stack else -1
        push arr[i]
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Each value is pushed and popped at most once.

    Edge cases

    • Equal values do not count as smaller.
    • Non-decreasing array such as [1, 2, 3]: every answer is -1.
    • One value.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int[] nextSmallerElement(int[] arr) {
            int n = arr.length;
            int[] out = new int[n];
            Deque<Integer> st = new ArrayDeque<>();         // candidates to the right, increasing from bottom to top
            for (int i = n - 1; i >= 0; i--) {              // walk from the right
                while (!st.isEmpty() && st.peek() >= arr[i]) st.pop();   // not smaller: useless for arr[i] and everything left
                out[i] = st.isEmpty() ? -1 : st.peek();
                st.push(arr[i]);
            }
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<int> nextSmallerElement(vector<int>& arr) {
            int n = static_cast<int>(arr.size());
            vector<int> out(n);
            stack<int> st;                                  // candidates to the right, increasing from bottom to top
            for (int i = n - 1; i >= 0; i--) {              // walk from the right
                while (!st.empty() && st.top() >= arr[i]) st.pop();   // not smaller: useless from here on
                out[i] = st.empty() ? -1 : st.top();
                st.push(arr[i]);
            }
            return out;
        }
    };

    Python

    class Solution:
        def nextSmallerElement(self, arr: list[int]) -> list[int]:
            out, st = [-1] * len(arr), []           # st: candidates to the right, increasing from bottom to top
            for i in range(len(arr) - 1, -1, -1):   # walk from the right
                while st and st[-1] >= arr[i]:
                    st.pop()                        # not smaller: useless for arr[i] and everything left
                out[i] = st[-1] if st else -1
                st.append(arr[i])
            return out

    Common mistakes

    • Using > instead of >=, which lets an equal value be the answer.
    • Reading the top before popping.

    Similar problems