# Next Smaller Element

Last Updated : 28 Dec, 2023

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

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

## Javascript

 ``

## PHP

 ` ``\$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` `?>`

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 ` `#include ` `#include `   `using` `namespace` `std ;`   `// function for finding next smaller element of every element in array `   `vector<``int``> findNextSmallerElement(``const` `std::vector<``int``>& arr) {` `  `  `  ``// declaring vector for storing next smaller element` `    ``vector<``int``> result(arr.size(), -1);  `   `  ``// declaring a stack` `    ``stack<``int``> st;  `   `  ``// iterating through array ` `    ``for` `(``int` `i = 0; i < arr.size(); ++i) {` `      `  `      ``// checking for next smaller element` `        ``while` `(!st.empty() && arr[i] < arr[st.top()]) {` `          `  `          ``// pushing the next smaller element` `            ``result[st.top()] = arr[i];` `          `  `            ``st.pop();` `        ``}`   `        ``// pushing elements of array in stack` `        ``st.push(i);` `    ``}`   `    ``return` `result;` `}`   `// main function` `int` `main() {` `  `  `  ``// array in which we have to find next smaller element` `    ``vector<``int``> arr = {4, 8, 2, 1, 6, 10, 5};` `  `  `// function calling` `    ``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 {`   `    ``// Function to print nearest smaller elements for each` `    ``// element in the array` `    ``static` `void` `printNSE(``int``[] arr)` `    ``{` `        ``int` `n = arr.length;` `        ``Stack stack` `            ``= ``new` `Stack<>(); ``// Stack to store indices of` `                             ``// elements` `        ``int``[] ans` `            ``= ``new` `int``[n]; ``// Array to store the results`   `        ``// Iterate through each element in the array` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``int` `next = arr[i];`   `            ``// Pop elements from the stack and update` `            ``// results for elements with smaller neighbors` `            ``while` `(!stack.isEmpty()` `                   ``&& arr[stack.peek()] > next) {` `                ``ans[stack.pop()] = next;` `            ``}`   `            ``// Push the current index onto the stack` `            ``stack.push(i);` `        ``}`   `        ``// For remaining elements in the stack, set their` `        ``// result to -1` `        ``while` `(!stack.isEmpty()) {` `            ``ans[stack.pop()] = -``1``;` `        ``}`   `        ``// Print the original array elements and their` `        ``// corresponding nearest smaller elements` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``System.out.println(arr[i] + ``" --> "` `+ ans[i]);` `        ``}` `    ``}`   `    ``// Driver program to test the function` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int``[] arr = { ``11``, ``13``, ``21``, ``3` `};` `        ``printNSE(arr);` `    ``}` `}`

## Python3

 `# Function to print the nearest smaller element for each element in the array` `def` `print_NSE(arr):` `    ``n ``=` `len``(arr)` `    ``stack ``=` `[]  ``# Stack to store indices of elements` `    ``ans ``=` `[``-``1``] ``*` `n  ``# Array to store the results, initialized with -1`   `    ``# Iterate through each element in the array` `    ``for` `i ``in` `range``(n):` `        ``next_val ``=` `arr[i]`   `        ``# Pop elements from the stack and update results for elements with smaller neighbors` `        ``while` `len``(stack) > ``0` `and` `arr[stack[``-``1``]] > next_val:` `            ``ans[stack.pop()] ``=` `next_val`   `        ``# Push the current index onto the stack` `        ``stack.append(i)` `        `  `    ``# Printing the original array` `    ``print``(``"Original Array is:"``, end``=``" "``)` `    ``for` `i ``in` `range``(n):` `        ``print``(``str``(arr[i]), end``=``" "``)`   `    ``# Printing the next smaller elements` `    ``print``(``"\nNext Smaller Elements:"``, end``=``" "``)` `    ``for` `i ``in` `range``(n):` `        ``print``(``str``(ans[i]), end``=``" "``)`   `# Driver program to test the function` `arr ``=` `[``4``, ``8``, ``2``, ``1``, ``6``, ``10``, ``5``]` `print_NSE(arr)`

## C#

 `using` `System;` `using` `System.Collections.Generic;`   `class` `NearestSmallerElement {` `    ``// Function to print the nearest smaller element for` `    ``// each element in the array` `    ``static` `void` `PrintNSE(``int``[] arr)` `    ``{` `        ``int` `n = arr.Length;` `        ``Stack<``int``> stack` `            ``= ``new` `Stack<``int``>(); ``// Stack to store indices of` `                                ``// elements` `        ``int``[] ans` `            ``= ``new` `int``[n]; ``// Array to store the results`   `        ``// Iterate through each element in the array` `        ``for` `(``int` `i = 0; i < n; i++) {` `            ``int` `next = arr[i];`   `            ``// Pop elements from the stack and update` `            ``// results for elements with smaller neighbors` `            ``while` `(stack.Count > 0` `                   ``&& arr[stack.Peek()] > next) {` `                ``ans[stack.Pop()] = next;` `            ``}`   `            ``// Push the current index onto the stack` `            ``stack.Push(i);` `        ``}`   `        ``// For remaining elements in the stack, set their` `        ``// result to -1` `        ``while` `(stack.Count > 0) {` `            ``ans[stack.Pop()] = -1;` `        ``}`   `        ``// Print the original array elements and their` `        ``// corresponding nearest smaller elements` `        ``for` `(``int` `i = 0; i < n; i++) {` `            ``Console.WriteLine(arr[i] + ``" --> "` `+ ans[i]);` `        ``}` `    ``}`   `    ``// Driver program to test the function` `    ``static` `void` `Main()` `    ``{` `        ``int``[] arr = { 11, 13, 21, 3 };` `        ``PrintNSE(arr);` `    ``}` `}`

## Javascript

 `// Function to print the nearest smaller element for each element in the array` `function` `printNSE(arr) {` `    ``const n = arr.length;` `    ``const stack = []; ``// Stack to store indices of elements` `    ``const ans = ``new` `Array(n); ``// Array to store the results`   `    ``// Iterate through each element in the array` `    ``for` `(let i = 0; i < n; i++) {` `        ``const next = arr[i];`   `        ``// Pop elements from the stack and update results for elements with smaller neighbors` `        ``while` `(stack.length > 0 && arr[stack[stack.length - 1]] > next) {` `            ``ans[stack.pop()] = next;` `        ``}`   `        ``// Push the current index onto the stack` `        ``stack.push(i);` `    ``}`   `    ``// For remaining elements in the stack, set their result to -1` `    ``while` `(stack.length > 0) {` `        ``ans[stack.pop()] = -1;` `    ``}`   `    ``// Print the original array elements and their corresponding nearest smaller elements` `    ``for` `(let i = 0; i < n; i++) {` `        ``console.log(arr[i] + ``" --> "` `+ ans[i]);` `    ``}` `}`   `// Driver program to test the function` `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)