Next Smaller of Next Greater

Last Updated : 9 Mar, 2026

Given an array arr[] of integers, find the next smaller element of the next greater element for each element in the array.

Note: Elements for which no greater element exists or no smaller of greater element exist, print -1.

Examples: 

Input : arr[] = [5, 1, 9, 2, 5, 1, 7]
Output: [2, 2, -1, 1, -1, -1, -1]
Explanation:

420851503

Input : arr[] = [4, 8, 2, 1, 9, 5, 6, 3]
Output : [2, 5, 5, 5, -1, 3, -1, -1]

Using Two For Loops - O(n) Time and O(1) Space

A simple approach is to iterate through each element of the array. For every element, first find its next greater element on the right, and then determine the next smaller element to the right of that greater element.

C++
//Driver Code Starts
#include <iostream>
#include <vector>
using namespace std;
//Driver Code Ends


vector<int> nextSmallerOfNextGreater(int arr[], int n)
{
    vector<int> result(n, -1);

    // For 1st n-1 elements of vector
    for (int i = 0; i < n - 1; i++)
    {

        int temp = arr[i];
        int next = -1;
        int ans = -1;

        // find the next greater
        for (int j = i + 1; j < n; j++)
        {
            if (arr[j] > temp)
            {
                next = j;
                break;
            }
        }

        if (next == -1)
        {
            result[i] = -1;
        }
        else
        {
            // find the next smaller of the next
            for (int j = next + 1; j < n; j++)
            {
                if (arr[j] < arr[next])
                {
                    ans = j;
                    break;
                }
            }
            if (ans == -1)
            {
                result[i] = -1;
            }
            else
            {
                result[i] = arr[ans];
            }
        }
    }

    return result;
}


//Driver Code Starts
int main()
{
    int arr[] = {5, 1, 9, 2, 5, 1, 7};
    int n = sizeof(arr) / sizeof(arr[0]);
    vector<int> result = nextSmallerOfNextGreater(arr, n);
    for (int x : result)
    {
        cout << x << " ";
    }
    cout << endl;
    return 0;
}
//Driver Code Ends
Java
//Driver Code Starts
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class GfG {

//Driver Code Ends

    static List<Integer> nextSmallerOfNextGreater(int[] arr,
                                                  int n)
    {

        List<Integer> result
            = new ArrayList<>(Collections.nCopies(n, -1));

        // For 1st n-1 elements of vector
        for (int i = 0; i < n - 1; i++) {

            int temp = arr[i];
            int next = -1;
            int ans = -1;

            // find the next greater
            for (int j = i + 1; j < n; j++) {
                if (arr[j] > temp) {
                    next = j;
                    break;
                }
            }

            if (next == -1) {
                result.set(i, -1);
            }
            else {

                // find the next smaller of the next
                for (int j = next + 1; j < n; j++) {
                    if (arr[j] < arr[next]) {
                        ans = j;
                        break;
                    }
                }

                if (ans == -1) {
                    result.set(i, -1);
                }
                else {
                    result.set(i, arr[ans]);
                }
            }
        }

        return result;
    }


//Driver Code Starts
    public static void main(String[] args)
    {

        int[] arr = { 5, 1, 9, 2, 5, 1, 7 };
        int n = arr.length;

        List<Integer> result
            = nextSmallerOfNextGreater(arr, n);

        for (int x : result) {
            System.out.print(x + " ");
        }

        System.out.println();
    }
}
//Driver Code Ends
Python
def nextSmallerOfNextGreater(arr, n):

    result = [-1] * n

    # For 1st n-1 elements of vector
    for i in range(n - 1):

        temp = arr[i]
        next = -1
        ans = -1

        # find the next greater
        for j in range(i + 1, n):
            if arr[j] > temp:
                next = j
                break

        if next == -1:
            result[i] = -1
        else:

            # find the next smaller of the next
            for j in range(next + 1, n):
                if arr[j] < arr[next]:
                    ans = j
                    break

            if ans == -1:
                result[i] = -1
            else:
                result[i] = arr[ans]

    return result


if __name__=="__main__":
#Driver Code Starts
    arr = [5, 1, 9, 2, 5, 1, 7]
    n = len(arr)
    
    result = nextSmallerOfNextGreater(arr, n)
    
    for x in result:
        print(x, end=" ")
#Driver Code Ends
C#
//Driver Code Starts
using System;
using System.Collections.Generic;

class GfG
{
//Driver Code Ends

    static List<int> nextSmallerOfNextGreater(int[] arr, int n)
    {
        List<int> result = new List<int>(new int[n]);

        for (int i = 0; i < n; i++)
            result[i] = -1;

        // For 1st n-1 elements of vector
        for (int i = 0; i < n - 1; i++)
        {
            int temp = arr[i];
            int next = -1;
            int ans = -1;

            // find the next greater
            for (int j = i + 1; j < n; j++)
            {
                if (arr[j] > temp)
                {
                    next = j;
                    break;
                }
            }

            if (next == -1)
            {
                result[i] = -1;
            }
            else
            {
                // find the next smaller of the next
                for (int j = next + 1; j < n; j++)
                {
                    if (arr[j] < arr[next])
                    {
                        ans = j;
                        break;
                    }
                }

                if (ans == -1)
                {
                    result[i] = -1;
                }
                else
                {
                    result[i] = arr[ans];
                }
            }
        }

        return result;
    }

//Driver Code Starts

    static void Main()
    {
        int[] arr = {5, 1, 9, 2, 5, 1, 7};
        int n = arr.Length;

        List<int> result = nextSmallerOfNextGreater(arr, n);

        foreach (int x in result)
        {
            Console.Write(x + " ");
        }

        Console.WriteLine();
    }
}
//Driver Code Ends
JavaScript
function nextSmallerOfNextGreater(arr, n) {

    let result = new Array(n).fill(-1);

    // For 1st n-1 elements of vector
    for (let i = 0; i < n - 1; i++) {

        let temp = arr[i];
        let next = -1;
        let ans = -1;

        // find the next greater
        for (let j = i + 1; j < n; j++) {
            if (arr[j] > temp) {
                next = j;
                break;
            }
        }

        if (next === -1) {
            result[i] = -1;
        } else {

            // find the next smaller of the next
            for (let j = next + 1; j < n; j++) {
                if (arr[j] < arr[next]) {
                    ans = j;
                    break;
                }
            }

            if (ans === -1) {
                result[i] = -1;
            } else {
                result[i] = arr[ans];
            }
        }
    }

    return result;
}


//Driver Code Starts
//Driver code
let arr = [5, 1, 9, 2, 5, 1, 7];
let n = arr.length;

let result = nextSmallerOfNextGreater(arr, n);

console.log(result.join(" "));
//Driver Code Ends

Output
2 2 -1 1 -1 -1 -1 

Using Monotonic Stack - O(n) Time and O(1) Space

The idea is to first determine the next greater element (NGE) for every element in the array. This can be efficiently done using a stack, which helps process elements in linear time while keeping track of indices whose next greater element has not yet been found.

Once the next greater element indices are stored, we then compute the next smaller element (NSE) for each element in the array using a similar stack-based approach.

Finally, we combine both results: for each element, we take its next greater element, and then find the next smaller element of that greater element. If any step does not exist, we return -1. This combined information gives us the next smaller element of the next greater element for every array element.

C++
//Driver Code Starts
#include <iostream>
#include <stack>
#include <vector>
using namespace std;

//Driver Code Ends

vector<int> nextSmallerOfNextGreater(int arr[], int n)
{
    // store index of next greater element
    vector<int> nge(n, -1); 
    
    // store value of next smaller element
    vector<int> nse(n, -1); 
    stack<int> st;
    vector<int> result(n, -1);
    
    // Find Next Greater Element index for each element
    for (int i = n - 1; i >= 0; i--)
    {
        while (!st.empty() && arr[st.top()] <= arr[i])
            st.pop();

        if (!st.empty())
            nge[i] = st.top();

        st.push(i);
    }

    // clear stack for next computation
    while (!st.empty())
        st.pop();

    // Find Next Smaller Element value for each element
    for (int i = n - 1; i >= 0; i--)
    {
        while (!st.empty() && arr[st.top()] >= arr[i])
            st.pop();

        if (!st.empty())
            nse[i] = arr[st.top()];

        st.push(i);
    }

    // Step 3: Combine results
    for (int i = 0; i < n; i++)
    {

        if (nge[i] == -1)
            continue;
        else
            result[i] = nse[nge[i]];
    }
    return result;
}


//Driver Code Starts
int main()
{
    int arr[] = {5, 1, 9, 2, 5, 1, 7};
    int n = sizeof(arr) / sizeof(arr[0]);
    vector<int>result=nextSmallerOfNextGreater(arr, n);
    for(int x:result){
        
        cout<<x<<" ";
    }
    
    cout<<endl;
    return 0;
}
//Driver Code Ends
Java
//Driver Code Starts
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Stack;

public class GfG {

    static ArrayList<Integer>
//Driver Code Ends

    nextSmallerOfNextGreater(int[] arr, int n)
    {

        int[] nge = new int[n];
        int[] nse = new int[n];

        Arrays.fill(nge, -1);
        Arrays.fill(nse, -1);

        Stack<Integer> st = new Stack<>();
        ArrayList<Integer> result
            = new ArrayList<>(Collections.nCopies(n, -1));

        // Next Greater Element index
        for (int i = n - 1; i >= 0; i--) {

            while (!st.isEmpty()
                   && arr[st.peek()] <= arr[i])
                st.pop();

            if (!st.isEmpty())
                nge[i] = st.peek();

            st.push(i);
        }

        st.clear();

        // Next Smaller Element value
        for (int i = n - 1; i >= 0; i--) {

            while (!st.isEmpty()
                   && arr[st.peek()] >= arr[i])
                st.pop();

            if (!st.isEmpty())
                nse[i] = arr[st.peek()];

            st.push(i);
        }

        // Combine results
        for (int i = 0; i < n; i++) {
            if (nge[i] != -1)
                result.set(i, nse[nge[i]]);
        }

        return result;
    }

//Driver Code Starts

    public static void main(String[] args)
    {

        int[] arr = { 5, 1, 9, 2, 5, 1, 7 };
        int n = arr.length;

        ArrayList<Integer> res
            = nextSmallerOfNextGreater(arr, n);

        for (int x : res)
            System.out.print(x + " ");
    }
}
//Driver Code Ends
Python
def nextSmallerOfNextGreater(arr):

    n = len(arr)

    nge = [-1] * n
    nse = [-1] * n
    result = [-1] * n

    stack = []

    # Next Greater Element index
    for i in range(n - 1, -1, -1):

        while stack and arr[stack[-1]] <= arr[i]:
            stack.pop()

        if stack:
            nge[i] = stack[-1]

        stack.append(i)

    stack.clear()

    # Next Smaller Element value
    for i in range(n - 1, -1, -1):

        while stack and arr[stack[-1]] >= arr[i]:
            stack.pop()

        if stack:
            nse[i] = arr[stack[-1]]

        stack.append(i)

    # Combine results
    for i in range(n):
        if nge[i] != -1:
            result[i] = nse[nge[i]]

    return result

if __name__=="__main__":
    arr = [5, 1, 9, 2, 5, 1, 7]
    
    res = nextSmallerOfNextGreater(arr)
    
    print(*res)
C#
//Driver Code Starts
using System;
using System.Collections.Generic;

class GfG{

//Driver Code Ends

    static List<int> nextSmallerOfNextGreater(int[] arr, int n) {

        int[] nge = new int[n];
        int[] nse = new int[n];

        for(int i = 0; i < n; i++) {
            nge[i] = -1;
            nse[i] = -1;
        }

        Stack<int> st = new Stack<int>();
        List<int> result = new List<int>(new int[n]);

        for(int i = 0; i < n; i++)
            result[i] = -1;

        // Next Greater Element index
        for(int i = n - 1; i >= 0; i--) {

            while(st.Count > 0 && arr[st.Peek()] <= arr[i])
                st.Pop();

            if(st.Count > 0)
                nge[i] = st.Peek();

            st.Push(i);
        }

        st.Clear();

        // Next Smaller Element value
        for(int i = n - 1; i >= 0; i--) {

            while(st.Count > 0 && arr[st.Peek()] >= arr[i])
                st.Pop();

            if(st.Count > 0)
                nse[i] = arr[st.Peek()];

            st.Push(i);
        }

        // Combine results
        for(int i = 0; i < n; i++) {
            if(nge[i] != -1)
                result[i] = nse[nge[i]];
        }

        return result;
    }

//Driver Code Starts

    static void Main() {

        int[] arr = {5, 1, 9, 2, 5, 1, 7};

        List<int> res = nextSmallerOfNextGreater(arr, arr.Length);

        foreach(int x in res)
            Console.Write(x + " ");
    }
}
//Driver Code Ends
JavaScript
function nextSmallerOfNextGreater(arr) {

    let n = arr.length;

    let nge = new Array(n).fill(-1);
    let nse = new Array(n).fill(-1);
    let result = new Array(n).fill(-1);

    let stack = [];

    // Next Greater Element index
    for (let i = n - 1; i >= 0; i--) {

        while (stack.length && arr[stack[stack.length - 1]] <= arr[i])
            stack.pop();

        if (stack.length)
            nge[i] = stack[stack.length - 1];

        stack.push(i);
    }

    stack = [];

    // Next Smaller Element value
    for (let i = n - 1; i >= 0; i--) {

        while (stack.length && arr[stack[stack.length - 1]] >= arr[i])
            stack.pop();

        if (stack.length)
            nse[i] = arr[stack[stack.length - 1]];

        stack.push(i);
    }

    // Combine
    for (let i = 0; i < n; i++) {
        if (nge[i] !== -1)
            result[i] = nse[nge[i]];
    }

    return result;
}


// Driver code
//Driver Code Starts
let arr = [5, 1, 9, 2, 5, 1, 7];

let res = nextSmallerOfNextGreater(arr);

console.log(res.join(" "));
//Driver Code Ends

Output
2 2 -1 1 -1 -1 -1 
Comment