Given an array, print the Next Smaller Element (NSE) for every element. The NSE for an element x is the first smaller element on the right side of x in the array. Elements for which no smaller element exist (on the right side), consider NSE as -1.
Examples:
Input: [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 4 having index > 3.
There are no elements smaller than 4 having index > 4.
Input: [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.
Next Smaller Element using two Nested 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.
Below is the implementation:
C++
#include "bits/stdc++.h"
using namespace std;
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;
}
}
int main()
{
int arr[]= {11, 13, 21, 3};
int n = sizeof (arr) / sizeof (arr[0]);
printNSE(arr, n);
return 0;
}
|
C
#include<stdio.h>
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
class Main {
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
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 ))
arr = [ 11 , 13 , 21 , 3 ]
printNSE(arr)
|
C#
using System;
class GFG {
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);
}
}
public static void Main()
{
int [] arr = { 11, 13, 21, 3 };
int n = arr.Length;
printNSE(arr, n);
}
}
|
Javascript
<script>
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>" );
}
}
var arr= [11, 13, 21, 3];
var n = arr.length;
printNSE(arr, n);
</script>
|
PHP
<?php
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" ;
}
}
$arr = array (11, 13, 21, 3);
$n = count ( $arr );
printNSE( $arr , $n );
?>
|
Output
11 --> 3
13 --> 3
21 --> 3
3 --> -1
Time Complexity: O(N^2) where N is the size of the input array.
Auxiliary Space: O(1)
Next Smaller Element 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). The idea is to store the indices of elements for which we have to find the next smaller element in a stack and while traversing the array, if we find a greater element, we will pair it with the elements from the stack till the top element of the stack is less than the current element.
- Pick the elements one by one and follow following steps in loop.
- Mark the current element as next.
- If stack is not empty, then compare next with stack top.
- If next is smaller than top then next is the NSE for the top. Keep popping from the stack while top is greater than next. This next will be the NSE for all such popped elements
- Push next into the stack
- After all the iterations, pop all the elements from stack and print -1 as next element for them.
Note: To achieve the same order, we store indices in the stack instead of values.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <stack>
#include <vector>
using namespace std ;
vector< int > findNextSmallerElement( const std::vector< int >& arr) {
vector< int > result(arr.size(), -1);
stack< int > st;
for ( int i = 0; i < arr.size(); ++i) {
while (!st.empty() && arr[i] < arr[st.top()]) {
result[st.top()] = arr[i];
st.pop();
}
st.push(i);
}
return result;
}
int main() {
vector< int > arr = {4, 8, 2, 1, 6, 10, 5};
vector< int > result = findNextSmallerElement(arr);
cout << "Original Array is: " ;
for ( int num : arr) {
cout << num << " " ;
}
cout << "\n Next Smaller Elements: " ;
for ( int num : result) {
cout << (num == -1 ? -1 : num) << " " ;
}
return 0;
}
|
Java
import java.util.Stack;
public class NearestSmallerElement {
static void printNSE( int [] arr)
{
int n = arr.length;
Stack<Integer> stack
= new Stack<>();
int [] ans
= new int [n];
for ( int i = 0 ; i < n; i++) {
int next = arr[i];
while (!stack.isEmpty()
&& arr[stack.peek()] > next) {
ans[stack.pop()] = next;
}
stack.push(i);
}
while (!stack.isEmpty()) {
ans[stack.pop()] = - 1 ;
}
for ( int i = 0 ; i < n; i++) {
System.out.println(arr[i] + " --> " + ans[i]);
}
}
public static void main(String[] args)
{
int [] arr = { 11 , 13 , 21 , 3 };
printNSE(arr);
}
}
|
Python3
def print_NSE(arr):
n = len (arr)
stack = []
ans = [ - 1 ] * n
for i in range (n):
next_val = arr[i]
while len (stack) > 0 and arr[stack[ - 1 ]] > next_val:
ans[stack.pop()] = next_val
stack.append(i)
print ( "Original Array is:" , end = " " )
for i in range (n):
print ( str (arr[i]), end = " " )
print ( "\nNext Smaller Elements:" , end = " " )
for i in range (n):
print ( str (ans[i]), end = " " )
arr = [ 4 , 8 , 2 , 1 , 6 , 10 , 5 ]
print_NSE(arr)
|
C#
using System;
using System.Collections.Generic;
class NearestSmallerElement {
static void PrintNSE( int [] arr)
{
int n = arr.Length;
Stack< int > stack
= new Stack< int >();
int [] ans
= new int [n];
for ( int i = 0; i < n; i++) {
int next = arr[i];
while (stack.Count > 0
&& arr[stack.Peek()] > next) {
ans[stack.Pop()] = next;
}
stack.Push(i);
}
while (stack.Count > 0) {
ans[stack.Pop()] = -1;
}
for ( int i = 0; i < n; i++) {
Console.WriteLine(arr[i] + " --> " + ans[i]);
}
}
static void Main()
{
int [] arr = { 11, 13, 21, 3 };
PrintNSE(arr);
}
}
|
Javascript
function printNSE(arr) {
const n = arr.length;
const stack = [];
const ans = new Array(n);
for (let i = 0; i < n; i++) {
const next = arr[i];
while (stack.length > 0 && arr[stack[stack.length - 1]] > next) {
ans[stack.pop()] = next;
}
stack.push(i);
}
while (stack.length > 0) {
ans[stack.pop()] = -1;
}
for (let i = 0; i < n; i++) {
console.log(arr[i] + " --> " + ans[i]);
}
}
const arr = [11, 13, 21, 3];
printNSE(arr);
|
Output
Original Array is: 4 8 2 1 6 10 5
Next Smaller Elements: 2 2 1 -1 5 5 -1
Time Complexity: O(N), where N is the size of input array
Auxiliary Space: O(N)
Last Updated :
28 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...