Skip to content
Related Articles

Related Articles

Improve Article

Next Smaller Element

  • Difficulty Level : Medium
  • Last Updated : 31 Aug, 2021

Given an array, print the Next Smaller Element (NSE) for every element. The Smaller smaller Element for an element x is the first smaller element on the right side of x in array. Elements for which no smaller element exist (on right side), consider next smaller element as -1. 
Examples: 
a) For any array, rightmost element always has next smaller element as -1. 
b) For an array which is sorted in increasing order, all elements have next smaller element as -1. 
c) For the input array [4, 8, 5, 2, 25}, the next smaller elements for each element are as follows.

Element       NSE
   4      -->   2
   8      -->   5
   5      -->   2
   2      -->   -1
   25     -->   -1

d) For the input array [13, 7, 6, 12}, the next smaller elements for each element are as follows.  

  Element        NSE
   13      -->    7
   7       -->    6
   6       -->    -1
   12     -->     -1

Method 1 (Simple) 
Use two loops: The outer loop picks all the elements one by one. The inner loop looks for the first smaller element for the element picked by outer loop. If a smaller element is found then that element is printed as next, otherwise, -1 is printed.
Thanks to Sachin for providing following code.  

C++




// Simple C++ program to print
// next smaller elements in a given array
#include "bits/stdc++.h"
using namespace std;
 
/* prints element and NSE pair
for all elements of arr[] of size n */
void printNSE(int arr[], int n)
{
    int next, i, j;
    for (i = 0; i < n; i++)
    {
        next = -1;
        for (j = i + 1; j < n; j++)
        {
            if (arr[i] > arr[j])
            {
                next = arr[j];
                break;
            }
        }
        cout << arr[i] << " -- "
             << next << endl;
    }
}
 
// Driver Code
int main()
{
    int arr[]= {11, 13, 21, 3};
    int n = sizeof(arr) / sizeof(arr[0]);
    printNSE(arr, n);
    return 0;
}
 
// This code is contributed by shivanisinghss2110

C




// Simple C program to print next smaller elements
// in a given array
#include<stdio.h>
 
/* prints element and NSE pair for all elements of
arr[] of size n */
void printNSE(int arr[], int n)
{
    int next, i, j;
    for (i=0; i<n; i++)
    {
        next = -1;
        for (j = i+1; j<n; j++)
        {
            if (arr[i] > arr[j])
            {
                next = arr[j];
                break;
            }
        }
        printf("%d -- %d\n", arr[i], next);
    }
}
 
int main()
{
    int arr[]= {11, 13, 21, 3};
    int n = sizeof(arr)/sizeof(arr[0]);
    printNSE(arr, n);
    return 0;
}

Java




// Simple Java program to print next
// smaller elements in a given array
 
class Main {
    /* prints element and NSE pair for
     all elements of arr[] of size n */
    static void printNSE(int arr[], int n)
    {
        int next, i, j;
        for (i = 0; i < n; i++) {
            next = -1;
            for (j = i + 1; j < n; j++) {
                if (arr[i] > arr[j]) {
                    next = arr[j];
                    break;
                }
            }
            System.out.println(arr[i] + " -- " + next);
        }
    }
 
    public static void main(String args[])
    {
        int arr[] = { 11, 13, 21, 3 };
        int n = arr.length;
        printNSE(arr, n);
    }
}

Python




# Function to print element and NSE pair for all elements of list
def printNSE(arr):
 
    for i in range(0, len(arr), 1):
 
        next = -1
        for j in range(i + 1, len(arr), 1):
            if arr[i] > arr[j]:
                next = arr[j]
                break
             
        print(str(arr[i]) + " -- " + str(next))
 
# Driver program to test above function
arr = [11, 13, 21, 3]
printNSE(arr)
 
# This code is contributed by Sunny Karira

C#




// Simple C# program to print next
// smaller elements in a given array
using System;
 
class GFG {
 
    /* prints element and NSE pair for
    all elements of arr[] of size n */
    static void printNSE(int[] arr, int n)
    {
        int next, i, j;
        for (i = 0; i < n; i++) {
            next = -1;
            for (j = i + 1; j < n; j++) {
                if (arr[i] > arr[j]) {
                    next = arr[j];
                    break;
                }
            }
            Console.WriteLine(arr[i] + " -- " + next);
        }
    }
 
    // driver code
    public static void Main()
    {
        int[] arr = { 11, 13, 21, 3 };
        int n = arr.Length;
 
        printNSE(arr, n);
    }
}
 
// This code is contributed by Sam007

PHP




<?php
// Simple PHP program to print next
// smaller elements in a given array
 
/* prints element and NSE pair for
   all elements of arr[] of size n */
function printNSE($arr, $n)
{
    for ($i = 0; $i < $n; $i++)
    {
        $next = -1;
        for ($j = $i + 1; $j < $n; $j++)
        {
            if ($arr[$i] > $arr[$j])
            {
                $next = $arr[$j];
                break;
            }
        }
        echo $arr[$i]." -- ". $next."\n";
         
    }
}
 
    // Driver Code
    $arr= array(11, 13, 21, 3);
    $n = count($arr);
    printNSE($arr, $n);
     
// This code is contributed by Sam007
?>

Javascript




<script>
 
// Simple Javascript program to print
// next smaller elements in a given array
 
/* prints element and NSE pair
for all elements of arr[] of size n */
function printNSE(arr, n)
{
    var next, i, j;
    for (i = 0; i < n; i++)
    {
        next = -1;
        for (j = i + 1; j < n; j++)
        {
            if (arr[i] > arr[j])
            {
                next = arr[j];
                break;
            }
        }
        document.write( arr[i] + " -- "
             + next+"<br>" );
    }
}
 
// Driver Code
var arr= [11, 13, 21, 3];  
var n = arr.length;
printNSE(arr, n);
 
</script>
Output: 
11 -- 3
13 -- 3
21 -- 3
3 -- -1

 

Time Complexity: O(n^2). The worst case occurs when all elements are sorted in decreasing order.
Method 2 (Using Stack) 
This problem is similar to next greater element. Here we maintain items in increasing order in the stack (instead of decreasing in next greater element problem).
1) Push the first element to stack. 
2) Pick rest of the elements one by one and follow following steps in loop. 
….a) Mark the current element as next
….b) If stack is not empty, then pop an element from stack and compare it with next
….c) If next is smaller than the popped element, then next is the next smaller element for the popped element. 
….d) Keep popping from the stack while the popped element is greater than next. next becomes the next smaller element for all such popped elements 
3) After the loop in step 2 is over, pop all the elements from stack and print -1 as next element for them.
 



C++




// A Stack based C++ program to find next
// smaller element for all array elements.
#include <bits/stdc++.h>
 
using namespace std;
 
/* prints element and NSE pair for all
elements of arr[] of size n */
void printNSE(int arr[], int n)
{
    stack<int> s;
 
    /* push the first element to stack */
    s.push(arr[0]);
 
    // iterate for rest of the elements
    for (int i = 1; i < n; i++) {
 
        if (s.empty()) {
            s.push(arr[i]);
            continue;
        }
 
        /* if stack is not empty, then
       pop an element from stack.
       If the popped element is greater
       than next, then
    a) print the pair
    b) keep popping while elements are
    greater and stack is not empty */
        while (s.empty() == false && s.top() > arr[i]) {
            cout << s.top() << " --> " << arr[i] << endl;
            s.pop();
        }
 
        /* push next to stack so that we can find
    next smaller for it */
        s.push(arr[i]);
    }
 
    /* After iterating over the loop, the remaining
  elements in stack do not have the next smaller
  element, so print -1 for them */
    while (s.empty() == false) {
        cout << s.top() << " --> " << -1 << endl;
        s.pop();
    }
}
 
/* Driver program to test above functions */
int main()
{
    int arr[] = { 11, 13, 21, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printNSE(arr, n);
    return 0;
}

Java




// A Stack based Java program to find next
// smaller element for all array elements.
import java.util.*;
import java.lang.*;
import java.io.*;
 
class GFG
{
    /* prints element and NSE pair for all
    elements of arr[] of size n */
    public static void printNSE(int arr[], int n)
    {
        Stack<Integer> s = new Stack<Integer>();
         
        /* push the first element to stack */
        s.push(arr[0]);
         
        // iterate for rest of the elements
        for (int i = 1; i < n; i++) {
 
        if (s.empty()) {
            s.push(arr[i]);
            continue;
        }
     
         
        /* if stack is not empty, then
        pop an element from stack.
        If the popped element is greater
        than next, then
        a) print the pair
        b) keep popping while elements are
        greater and stack is not empty */
    while (s.empty() == false && s.peek() > arr[i]) {
            System.out.println(s.peek() + " --> " + arr[i]);
            s.pop();
        }
         
        /* push next to stack so that we can find
        next smaller for it */
        s.push(arr[i]);
        }
         
        /* After iterating over the loop, the remaining
        elements in stack do not have the next smaller
        element, so print -1 for them */
            while (s.empty() == false) {
        System.out.println(s.peek() + " --> " + "-1");
        s.pop();
        }
    }
    /* Driver program to test above functions */
    public static void main (String[] args) {
        int arr[] = { 11, 13, 21, 3};
        int n = arr.length;
        printNSE(arr, n);
    }
}

Python3




#  A Stack based Python program to find
#  "Next Smaller Element" for all array elements
#  in same order as input.
 
 
# function  take argument 1. array and 2.size of array
def NSE(arr, n):
 
    # An empty stack
    stack = []
    # A list where we store the result
 
    result = []
    # iterate over the array
    for i in range(n-1, -1, -1):
 
        # if length of stack is not zero
        # and top of stack is greater than current array element
        # then pop till the smaller element found in stack top
 
        # Note:- here current means i
 
        while len(stack) > 0 and arr[i] < stack[-1]:
            stack.pop()
 
        # if the length of stack is zero then it means
        # there are no any element less than current
        # so add -1 to result.
 
        if len(stack) == 0:
            result.append(-1)
 
        # if length of stack is not zero than
        # it means top of stack is next smaller element for current
 
        else:
            result.append(stack[-1])
 
        # push next current to stack
        stack.append(arr[i])
 
    # we have to reverse result because
    # we have stored the element in result in reverse order
    result = result[-1::-1]
 
    return result
 
#  Driver program to test above functions
 
 
arr = [11, 13, 21, 3]
n = len(arr)
result = NSE(arr, n)
for i in range(n):
    print(str(arr[i]) + "   --->  " + str(result[i]))
 
# This code is contributed by Ritesh Vishwakarma

C#




// A Stack based C# program to find next
// smaller element for all array elements.
using System;
using System.Collections.Generic;
public class GFG
{
    /* prints element and NSE pair for all
    elements of arr[] of size n */
    public static void printNSE(int []arr, int n)
    {
        Stack<int> s = new Stack<int>();
          
        /* push the first element to stack */
        s.Push(arr[0]);
          
        // iterate for rest of the elements
        for (int i = 1; i < n; i++) {
  
        if (s.Count==0) {
            s.Push(arr[i]);
            continue;
        }
      
          
        /* if stack is not empty, then
        pop an element from stack.
        If the popped element is greater
        than next, then
        a) print the pair
        b) keep popping while elements are
        greater and stack is not empty */
    while (s.Count !=0 && s.Peek() > arr[i]) {
            Console.WriteLine(s.Peek() + " --> " + arr[i]);
            s.Pop();
        }
          
        /* push next to stack so that we can find
        next smaller for it */
        s.Push(arr[i]);
        }
          
        /* After iterating over the loop, the remaining
        elements in stack do not have the next smaller
        element, so print -1 for them */
            while (s.Count!=0) {
        Console.WriteLine(s.Peek() + " --> " + "-1");
        s.Pop();
        }
    }
    /* Driver program to test above functions */
    public static void Main () {
        int []arr = { 11, 13, 21, 3};
        int n = arr.Length;
        printNSE(arr, n);
    }
}
//This code is contributed by PrinciRaj1992

Javascript




<script>
// A Stack based Javascript program to find next
// smaller element for all array elements.
 
/* prints element and NSE pair for all
    elements of arr[] of size n */
function printNSE(arr,n)
{
     let s = [];
          
        /* push the first element to stack */
        s.push(arr[0]);
          
        // iterate for rest of the elements
        for (let i = 1; i < n; i++) {
  
        if (s.length==0) {
            s.push(arr[i]);
            continue;
        }
      
          
        /* if stack is not empty, then
        pop an element from stack.
        If the popped element is greater
        than next, then
        a) print the pair
        b) keep popping while elements are
        greater and stack is not empty */
    while (s.length != 0 && s[s.length-1] > arr[i]) {
            document.write(s[s.length-1] + " --> " + arr[i]+"<br>");
            s.pop();
        }
          
        /* push next to stack so that we can find
        next smaller for it */
        s.push(arr[i]);
        }
          
        /* After iterating over the loop, the remaining
        elements in stack do not have the next smaller
        element, so print -1 for them */
            while (s.length != 0) {
        document.write(s[s.length-1] + " --> " + "-1<br>");
        s.pop();
        }
}
 
/* Driver program to test above functions */
let arr=[11, 13, 21, 3];
let n = arr.length;
printNSE(arr, n);
 
// This code is contributed by patel2127
</script>
Output: 
21 --> 3
13 --> 3
11 --> 3
3 --> -1

 

Time Complexity: O(n). The worst case occurs when all elements are sorted in increasing order. If elements are sorted in increasing order, then every element is processed at most 4 times. 
a) Initially pushed to the stack. 
b) Popped from the stack when next element is being processed. 
c) Pushed back to the stack because next element is smaller. 
d) Popped from the stack in step 3 of algo.
How to get elements in same order as input? 
The above approach may not produce output elements in same order as input. To achieve same order, we can use an unordered_map in C++ (or HashMap in Java).
 

C++




// A Stack based C++ program to find next
// smaller element for all array elements
// in same order as input.
#include <bits/stdc++.h>
using namespace std;
 
/* prints element and NSE pair for all
elements of arr[] of size n */
void printNSE(int arr[], int n)
{
    stack<int> s;
    unordered_map<int, int> mp;
 
    /* push the first element to stack */
    s.push(arr[0]);
     
 
    // iterate for rest of the elements
    for (int i = 1; i < n; i++) {
 
        if (s.empty()) {
            s.push(arr[i]);
            continue;
        }
 
        /* if stack is not empty, then
       pop an element from stack.
       If the popped element is greater
       than next, then
    a) print the pair
    b) keep popping while elements are
    greater and stack is not empty */
        while (s.empty() == false && s.top() > arr[i]) {
            mp[s.top()] = arr[i];
            s.pop();
        }
 
        /* push next to stack so that we can find
    next smaller for it */
        s.push(arr[i]);
    }
 
    /* After iterating over the loop, the remaining
  elements in stack do not have the next smaller
  element, so print -1 for them */
    while (s.empty() == false) {
         mp[s.top()] = -1;
        s.pop();
    }
 
    for (int i=0; i<n; i++)
       cout << arr[i] << " ---> " << mp[arr[i]] << endl;
}
 
/* Driver program to test above functions */
int main()
{
    int arr[] = { 11, 13, 21, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printNSE(arr, n);
    return 0;
}

Java




// A Stack based Java program to find next
// smaller element for all array elements
// in same order as input.
import java.util.*;
import java.lang.*;
import java.io.*;
 
class GFG
{
    /* prints element and NSE pair for all
    elements of arr[] of size n */
public static void printNSE(int arr[], int n)
{
    Stack<Integer> s = new Stack<Integer>();
    HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
         
    /* push the first element to stack */
    s.push(arr[0]);
         
         
    // iterate for rest of the elements
    for (int i = 1; i < n; i++) {
 
        if (s.empty()) {
            s.push(arr[i]);
            continue;
        }
         
         
        /* if stack is not empty, then
    pop an element from stack.
    If the popped element is greater
    than next, then
    a) print the pair
    b) keep popping while elements are
    greater and stack is not empty */
     
    while (s.empty() == false && s.peek() > arr[i]) {
            mp.put(s.peek(), arr[i]);
            s.pop();
        }
         
        /* push next to stack so that we can find
        next smaller for it */
        s.push(arr[i]);
    }
         
         
         
    /* After iterating over the loop, the remaining
    elements in stack do not have the next smaller
    element, so print -1 for them */
    while (s.empty() == false) {
        mp.put(s.peek(), -1);
        s.pop();
    }
     
     
    for (int i=0; i<n; i++)
    System.out.println(arr[i] + " ---> " + mp.get(arr[i]));
}
     
    /* Driver program to test above functions */
    public static void main (String[] args) {
        int arr[] = { 11, 13, 21, 3};
        int n = arr.length;
        printNSE(arr, n);
    }
}

Python3




# A Stack based Python3 program to find next
# smaller element for all array elements
# in same order as input.using System;
 
""" prints element and NSE pair for all
elements of arr[] of size n """
def printNSE(arr, n):
    s = []
    mp = {}
 
    # push the first element to stack
    s.append(arr[0])
 
 
    # iterate for rest of the elements
    for i in range(1, n):
        if (len(s) == 0):
            s.append(arr[i])
            continue
             
        """ if stack is not empty, then
        pop an element from stack.
        If the popped element is greater
        than next, then
        a) print the pair
        b) keep popping while elements are
        greater and stack is not empty """
        while (len(s) != 0 and s[-1] > arr[i]):
            mp[s[-1]] = arr[i]
            s.pop()
 
        """ push next to stack so that we can find
        next smaller for it """
        s.append(arr[i])
 
    """ After iterating over the loop, the remaining
    elements in stack do not have the next smaller
    element, so print -1 for them """
    while (len(s) != 0):
        mp[s[-1]] = -1
        s.pop()
 
    for i in range(n):
        print(arr[i], "--->", mp[arr[i]])
 
arr = [11, 13, 21, 3]
n = len(arr)
printNSE(arr, n)
 
# This code is contributed by decode2207.

C#




// A Stack based C# program to find next
// smaller element for all array elements
// in same order as input.using System;
using System;
using System.Collections.Generic;
 
class GFG
{
    /* prints element and NSE pair for all
    elements of arr[] of size n */
    public static void printNSE(int []arr, int n)
    {
        Stack<int> s = new Stack<int>();
        Dictionary<int, int> mp = new Dictionary<int, int>();
 
        /* push the first element to stack */
        s.Push(arr[0]);
 
 
        // iterate for rest of the elements
        for (int i = 1; i < n; i++)
        {
            if (s.Count==0)
            {
                s.Push(arr[i]);
                continue;
            }
            /* if stack is not empty, then
            pop an element from stack.
            If the popped element is greater
            than next, then
            a) print the pair
            b) keep popping while elements are
            greater and stack is not empty */
            while (s.Count != 0 && s.Peek() > arr[i])
            {
                mp.Add(s.Peek(), arr[i]);
                s.Pop();
            }
 
            /* push next to stack so that we can find
            next smaller for it */
            s.Push(arr[i]);
        }
 
 
 
        /* After iterating over the loop, the remaining
        elements in stack do not have the next smaller
        element, so print -1 for them */
        while (s.Count != 0)
        {
            mp.Add(s.Peek(), -1);
            s.Pop();
        }
 
 
        for (int i = 0; i < n; i++)
        Console.WriteLine(arr[i] + " ---> " + mp[arr[i]]);
    }
     
    // Driver code
    public static void Main()
    {
        int []arr = {11, 13, 21, 3};
        int n = arr.Length;
        printNSE(arr, n);
    }
}
// This code is contributed by
// 29AjayKumar

Javascript




<script>
    // A Stack based Javascript program to find next
    // smaller element for all array elements
    // in same order as input.
     
    /* prints element and NSE pair for all
    elements of arr[] of size n */
    function printNSE(arr, n)
    {
        let s = [];
        let mp = new Map();
  
        /* push the first element to stack */
        s.push(arr[0]);
  
  
        // iterate for rest of the elements
        for (let i = 1; i < n; i++)
        {
            if (s.length==0)
            {
                s.push(arr[i]);
                continue;
            }
            /* if stack is not empty, then
            pop an element from stack.
            If the popped element is greater
            than next, then
            a) print the pair
            b) keep popping while elements are
            greater and stack is not empty */
            while (s.length != 0 && s[s.length - 1] > arr[i])
            {
                mp[s[s.length - 1]] = arr[i];
                s.pop();
            }
  
            /* push next to stack so that we can find
            next smaller for it */
            s.push(arr[i]);
        }
  
  
  
        /* After iterating over the loop, the remaining
        elements in stack do not have the next smaller
        element, so print -1 for them */
        while (s.length != 0)
        {
            mp[s[s.length - 1]] = -1;
            s.pop();
        }
  
  
        for (let i = 0; i < n; i++)
            document.write(arr[i] + " ---> " + mp[arr[i]] + "</br>");
    }
     
    let arr = [11, 13, 21, 3];
    let n = arr.length;
    printNSE(arr, n);
     
    // This code is contributed by divyesh072019.
</script>
Output: 
11 ---> 3
13 ---> 3
21 ---> 3
3 ---> -1

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :