Next Smaller Element

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

filter_none

edit
close

play_arrow

link
brightness_4
code

       
// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

   
# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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
?>

chevron_right


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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 smaller
       than next, then
    a) print the pair
    b) keep popping while elements are
    smaller 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 smaller
        than next, then
        a) print the pair
        b) keep popping while elements are
        smaller 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);
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 smaller
        than next, then
        a) print the pair
        b) keep popping while elements are
        smaller 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

chevron_right


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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 smaller
       than next, then
    a) print the pair
    b) keep popping while elements are
    smaller 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 smaller
    than next, then
    a) print the pair
    b) keep popping while elements are
    smaller 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);
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 smaller
            than next, then
            a) print the pair
            b) keep popping while elements are
            smaller 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

chevron_right


Output:

11 ---> 3
13 ---> 3
21 ---> 3
3 ---> -1


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.