Next Smaller Element (original) (raw)

Last Updated : 15 Sep, 2025

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.

Try It Yourselfredirect icon

Table of Content

[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.

C++ `

#include #include using namespace std;

vector nextSmallerEle(vector& arr) { int n = arr.size();

// initialize all NSEs as -1
vector<int> result(n, -1); 

for (int i = 0; i < n; i++) {
    for (int j = i + 1; j < n; j++) {
        if (arr[j] < arr[i]) {
          
            // first smaller element on the right
            result[i] = arr[j]; 
            break;
        }
    }
}

return result;

}

int main() { vector arr = {4, 8, 5, 2, 25}; vector nse = nextSmallerEle(arr);

for (int x : nse) {
    cout << x << " ";
}
cout << endl;

return 0;

}

C

#include <stdio.h> #include <stdlib.h>

int* nextSmallerEle(int arr[], int n) {

// allocate memory for result array
int* result = (int*)malloc(n * sizeof(int));

// initialize all NSEs as -1
for (int i = 0; i < n; i++) {
    result[i] = -1;
}

// check for next smaller element for each element
for (int i = 0; i < n; i++) {
    for (int j = i + 1; j < n; j++) {
        if (arr[j] < arr[i]) {

            // first smaller element on the right
            result[i] = arr[j];
            break;
        }
    }
}

return result;

}

int main() { int arr[] = {4, 8, 5, 2, 25}; int n = sizeof(arr) / sizeof(arr[0]);

int* result = nextSmallerEle(arr, n);

for (int i = 0; i < n; i++) {
    printf("%d ", result[i]);
}
printf("\n");

return 0;

}

Java

import java.util.ArrayList;

class GfG { static ArrayList nextSmallerEle(int[] arr) { int n = arr.length;

    // initialize all NSEs as -1
    ArrayList<Integer> result = new ArrayList<>();
    for (int i = 0; i < n; i++) result.add(-1);

    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[i]) {

                // first smaller element on the right
                result.set(i, arr[j]);
                break;
            }
        }
    }

    return result;
}

public static void main(String[] args) {
    int[] arr = {4, 8, 5, 2, 25};
    ArrayList<Integer> nse = nextSmallerEle(arr);

    for (int x : nse) System.out.print(x + " ");
    System.out.println();
}

}

Python

def nextSmallerEle(arr): n = len(arr)

# initialize all NSEs as -1
result = [-1] * n

for i in range(n):
    for j in range(i + 1, n):
        if arr[j] < arr[i]:

            # first smaller element on the right
            result[i] = arr[j]
            break

return result

if name == "main": arr = [4, 8, 5, 2, 25] nse = nextSmallerEle(arr)

for x in nse:
    print(x, end=" ")
print()  

C#

using System; using System.Collections.Generic;

class GfG { public static List nextSmallerEle(int[] arr) { int n = arr.Length;

    // initialize all NSEs as -1
    List<int> result = new List<int>();
    for (int i = 0; i < n; i++) result.Add(-1);

    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[i]) {

                // first smaller element on the right
                result[i] = arr[j];
                break;
            }
        }
    }
    return result;
}

public static void Main() {
    int[] arr = {4, 8, 5, 2, 25};
    List<int> nse = nextSmallerEle(arr);

    foreach (int x in nse) Console.Write(x + " ");
    Console.WriteLine();
}

}

JavaScript

function nextSmallerEle(arr) { let n = arr.length;

// initialize all NSEs as -1
let result = new Array(n).fill(-1);

for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
        if (arr[j] < arr[i]) {

            // first smaller element on the right
            result[i] = arr[j];
            break;
        }
    }
}

return result;

}

// Driver Code let arr = [4, 8, 5, 2, 25]; let nse = nextSmallerEle(arr); console.log(nse.join(" "));

`

[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.

C++ `

#include #include #include using namespace std;

vector nextSmallerEle(vector& arr) { int n = arr.size();

// initialize all NSEs as -1
vector<int> result(n, -1); 

stack<int> st; 

// traverse the array from right to left
for (int i = n - 1; i >= 0; i--) {
    
    // pop elements from stack which are >= current element
    while (!st.empty() && st.top() >= arr[i]) {
        st.pop();
    }

    // if stack is not empty, top element is NSE
    if (!st.empty()) {
        result[i] = st.top();
    }

    // push current element onto stack
    st.push(arr[i]);
}

return result;

}

int main() { vector arr = {4, 8, 5, 2, 25}; vector nse = nextSmallerEle(arr);

for (int x : nse) {
    cout << x << " ";
}
cout << endl;

return 0;

}

Java

import java.util.ArrayList; import java.util.Stack;

class GfG { static ArrayList nextSmallerEle(int[] arr) { int n = arr.length;

    // initialize all NSEs as -1
    ArrayList<Integer> result = new ArrayList<>();
    for (int i = 0; i < n; i++) result.add(-1);

    Stack<Integer> st = new Stack<>();

    // traverse the array from right to left
    for (int i = n - 1; i >= 0; i--) {

        // pop elements from stack which are >= current element
        while (!st.isEmpty() && st.peek() >= arr[i]) {
            st.pop();
        }

        // if stack is not empty, top element is NSE
        if (!st.isEmpty()) {
            result.set(i, st.peek());
        }

        // push current element onto stack
        st.push(arr[i]);
    }

    return result;
}

public static void main(String[] args) {
    int[] arr = {4, 8, 5, 2, 25};
    ArrayList<Integer> nse = nextSmallerEle(arr);

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

}

Python

def nextSmallerEle(arr): n = len(arr)

# initialize all NSEs as -1
result = [-1] * n

st = []

# traverse the array from right to left
for i in range(n - 1, -1, -1):

    # pop elements from stack which are >= current element
    while st and st[-1] >= arr[i]:
        st.pop()

    # if stack is not empty, top element is NSE
    if st:
        result[i] = st[-1]

    # push current element onto stack
    st.append(arr[i])

return result

if name == "main": arr = [4, 8, 5, 2, 25] nse = nextSmallerEle(arr)

for x in nse:
    print(x, end=" ")
print()

C#

using System; using System.Collections.Generic;

class GFG { static List nextSmallerEle(int[] arr) { int n = arr.Length;

    // initialize all NSEs as -1
    List<int> result = new List<int>();
    for (int i = 0; i < n; i++) result.Add(-1);

    Stack<int> st = new Stack<int>();

    // traverse the array from right to left
    for (int i = n - 1; i >= 0; i--) {

        // pop elements from stack which are >= current element
        while (st.Count > 0 && st.Peek() >= arr[i]) {
            st.Pop();
        }

        // if stack is not empty, top element is NSE
        if (st.Count > 0) {
            result[i] = st.Peek();
        }

        // push current element onto stack
        st.Push(arr[i]);
    }

    return result;
}

static void Main() {
    int[] arr = {4, 8, 5, 2, 25};
    List<int> nse = nextSmallerEle(arr);

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

}

JavaScript

function nextSmallerEle(arr) { let n = arr.length;

// initialize all NSEs as -1
let result = new Array(n).fill(-1);

let st = [];

// traverse the array from right to left
for (let i = n - 1; i >= 0; i--) {

    // pop elements from stack which are >= current element
    while (st.length > 0 && st[st.length - 1] >= arr[i]) {
        st.pop();
    }

    // if stack is not empty, top element is NSE
    if (st.length > 0) {
        result[i] = st[st.length - 1];
    }

    // push current element onto stack
    st.push(arr[i]);
}

return result;

}

// Example usage let arr = [4, 8, 5, 2, 25]; let nse = nextSmallerEle(arr); console.log(nse.join(" "));

`