Next Smaller Element
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:
a) For any array, the rightmost element always has NSE as -1.
b) For an array that is sorted in increasing order, all elements have NSE as -1.
c) For the input array [4, 8, 5, 2, 25}, the NSE for each element is 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.
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> |
11 -- 3 13 -- 3 21 -- 3 3 -- -1
Time Complexity:
: The worst case occurs when all elements are sorted in increasing order.
Auxiliary Space: O(1): As constant extra space is used
Method 2 (Using Segment Tree and Binary Search)
This method is also pretty simple if one knows Segment trees and Binary Search. Lets consider an array and lets suppose NSE for
is
, we simply need to binary search for
in range
to
.
will be the first index
, such that range minimum of elements from index
to
(
) is lesser than
.
Example
C++
#include <bits/stdc++.h> using namespace std; // Program to find next smaller element for all elements in // an array, using segment tree and binary search // --------Segment Tree Starts Here----------------- vector< int > seg_tree; // combine function for combining two nodes of the tree, in // this case we need to take min of two int combine( int a, int b) { return min(a, b); } // build function, builds seg_tree based on vector parameter // arr void build(vector< int >& arr, int node, int tl, int tr) { // if current range consists only of one element, then // node should be this element if (tl == tr) { seg_tree[node] = arr[tl]; } else { // divide the build operations into two parts int tm = (tr - tl) / 2 + tl; build(arr, 2 * node, tl, tm ); build(arr, 2 * node + 1, tm + 1, tr); // combine the results from two parts, and store it // into current node seg_tree[node] = combine(seg_tree[2 * node], seg_tree[2 * node + 1]); } } // query function, returns minimum in the range [l, r] int query( int node, int tl, int tr, int l, int r) { // if range is invalid, then return infinity if (l > r) { return INT32_MAX; } // if range completely aligns with a segment tree node, // then value of this node should be returned if (l == tl && r == tr) { return seg_tree[node]; } // else divide the query into two parts int tm = (tr - tl) / 2 + tl; int q1 = query(2 * node, tl, tm , l, min(r, tm )); int q2 = query(2 * node + 1, tm + 1, tr, max(l, tm + 1), r); // and combine the results from the two parts and return // it return combine(q1, q2); } // --------Segment Tree Ends Here----------------- void printNSE(vector< int > arr, int n) { seg_tree = vector< int >(4 * n); // build segment tree initially build(arr, 1, 0, n - 1); int q, l, r, mid, ans; for ( int i = 0; i < n; i++) { // binary search for ans in range [i + 1, n - 1], // initially ans is -1 representing there is no NSE // for this element l = i + 1; r = n - 1; ans = -1; while (l <= r) { mid = (r - l) / 2 + l; // q is the minimum element in range [l, mid] q = query(1, 0, n - 1, l, mid); // if the minimum element in range [l, mid] is // less than arr[i], then mid can be answer, we // mark it, and look for a better answer in left // half. Else if q is greater than arr[i], mid // can't be an answer, we should search in right // half if (q < arr[i]) { ans = arr[mid]; r = mid - 1; } else { l = mid + 1; } } // print NSE for arr[i] cout << arr[i] << " ---> " << ans << "\n" ; } } // Driver program to test above functions int main() { vector< int > arr = { 11, 13, 21, 3 }; printNSE(arr, 4); return 0; } |
Java
// Program to find next smaller element for all elements in // an array, using segment tree and binary search // --------Segment Tree Starts Here----------------- import java.util.*; class GFG { static int [] seg_tree; // combine function for combining two nodes of the tree, in // this case we need to take min of two static int combine( int a, int b) { return Math.min(a, b); } // build function, builds seg_tree based on vector parameter // arr static void build( int [] arr, int node, int tl, int tr) { // if current range consists only of one element, then // node should be this element if (tl == tr) { seg_tree[node] = arr[tl]; } else { // divide the build operations into two parts int tm = (tr - tl) / 2 + tl; build(arr, 2 * node, tl, tm); build(arr, 2 * node + 1 , tm + 1 , tr); // combine the results from two parts, and store it // into current node seg_tree[node] = combine(seg_tree[ 2 * node],seg_tree[ 2 * node + 1 ]); } } // query function, returns minimum in the range [l, r] static int query( int node, int tl, int tr, int l, int r) { // if range is invalid, then return infinity if (l > r) { return Integer.MAX_VALUE; } // if range completely aligns with a segment tree node, // then value of this node should be returned if (l == tl && r == tr) { return seg_tree[node]; } // else divide the query into two parts int tm = (tr - tl) / 2 + tl; int q1 = query( 2 * node, tl, tm, l, Math.min(r, tm)); int q2 = query( 2 * node + 1 , tm + 1 , tr, Math.max(l, tm + 1 ),r); // and combine the results from the two parts and return // it return combine(q1, q2); } // --------Segment Tree Ends Here----------------- static void printNSE( int [] arr, int n) { seg_tree = new int [ 4 * n]; // build segment tree initially build(arr, 1 , 0 , n - 1 ); int q, l, r, mid, ans; for ( int i = 0 ; i < n; i++) { // binary search for ans in range [i + 1, n - 1], // initially ans is -1 representing there is no NSE // for this element l = i + 1 ; r = n - 1 ; ans = - 1 ; while (l <= r) { mid = (r - l) / 2 + l; // q is the minimum element in range [l, mid] q = query( 1 , 0 , n - 1 , l, mid); // if the minimum element in range [l, mid] is // less than arr[i], then mid can be answer, we // mark it, and look for a better answer in left // half. Else if q is greater than arr[i], mid // can't be an answer, we should search in right // half if (q < arr[i]) { ans = arr[mid]; r = mid - 1 ; } else { l = mid + 1 ; } } // print NSE for arr[i] System.out.println(arr[i] + " ---> " + ans); } } public static void main(String[] args) { int [] arr = { 11 , 13 , 21 , 3 }; printNSE(arr, 4 ); } } // This code is contributed by aadityaburujwale. |
Python3
# Program to find next smaller element for all elements in # an array, using segment tree and binary search import math # --------Segment Tree Starts Here----------------- seg_tree = [] def combine(a, b): return min (a, b) def build(arr, node, tl, tr): # if current range consists only of one element, then # node should be this element if tl = = tr: seg_tree[node] = arr[tl] else : # divide the build operations into two parts tm = (tr - tl) / / 2 + tl build(arr, 2 * node, tl, tm) build(arr, 2 * node + 1 , tm + 1 , tr) # combine the results from two parts, and store it # into current node seg_tree[node] = combine(seg_tree[ 2 * node], seg_tree[ 2 * node + 1 ]) def query(node, tl, tr, l, r): # if range is invalid, then return infinity if l > r: return float ( 'inf' ) # if range completely aligns with a segment tree node, # then value of this node should be returned if l = = tl and r = = tr: return seg_tree[node] # else divide the query into two parts tm = (tr - tl) / / 2 + tl q1 = query( 2 * node, tl, tm, l, min (r, tm)) q2 = query( 2 * node + 1 , tm + 1 , tr, max (l, tm + 1 ), r) # and combine the results from the two parts and return # it return combine(q1, q2) # --------Segment Tree Ends Here----------------- def printNSE(arr, n): global seg_tree seg_tree = [ 0 ] * ( 4 * n) # build segment tree initially build(arr, 1 , 0 , n - 1 ) for i in range (n): # binary search for ans in range [i + 1, n - 1], # initially ans is -1 representing there is no NSE # for this element l = i + 1 r = n - 1 ans = - 1 while l < = r: mid = (r - l) / / 2 + l # q is the minimum element in range [l, mid] q = query( 1 , 0 , n - 1 , l, mid) # if the minimum element in range [l, mid] is # less than arr[i], then mid can be answer, we # mark it, and look for a better answer in left # half. Else if q is greater than arr[i], mid # can't be an answer, we should search in right # half if q < arr[i]: ans = arr[mid] r = mid - 1 else : l = mid + 1 # print NSE for arr[i] print (arr[i], "-->" , ans) arr = [ 11 , 13 , 21 , 3 ] printNSE(arr, 4 ) # This code is contributed by lokeshmvs21. |
C#
// Program to find next smaller element for all elements in // an array, using segment tree and binary search // --------Segment Tree Starts Here----------------- using System; public class GFG { static int [] seg_tree; // combine function for combining two nodes of the tree, // in // this case we need to take min of two static int combine( int a, int b) { return Math.Min(a, b); } // build function, builds seg_tree based on vector // parameter arr static void build( int [] arr, int node, int tl, int tr) { // if current range consists only of one element, // then node should be this element if (tl == tr) { seg_tree[node] = arr[tl]; } else { // divide the build operations into two parts int tm = (tr - tl) / 2 + tl; build(arr, 2 * node, tl, tm); build(arr, 2 * node + 1, tm + 1, tr); // combine the results from two parts, and store // it into current node seg_tree[node] = combine( seg_tree[2 * node], seg_tree[2 * node + 1]); } } // query function, returns minimum in the range [l, r] static int query( int node, int tl, int tr, int l, int r) { // if range is invalid, then return infinity if (l > r) { return Int32.MaxValue; } // if range completely aligns with a segment tree // node, then value of this node should be returned if (l == tl && r == tr) { return seg_tree[node]; } // else divide the query into two parts int tm = (tr - tl) / 2 + tl; int q1 = query(2 * node, tl, tm, l, Math.Min(r, tm)); int q2 = query(2 * node + 1, tm + 1, tr, Math.Max(l, tm + 1), r); // and combine the results from the two parts and // return it return combine(q1, q2); } // --------Segment Tree Ends Here----------------- static void printNSE( int [] arr, int n) { seg_tree = new int [4 * n]; // build segment tree initially build(arr, 1, 0, n - 1); int q, l, r, mid, ans; for ( int i = 0; i < n; i++) { // binary search for ans in range [i + 1, n - // 1], initially ans is -1 representing there is // no NSE for this element l = i + 1; r = n - 1; ans = -1; while (l <= r) { mid = (r - l) / 2 + l; // q is the minimum element in range [l, // mid] q = query(1, 0, n - 1, l, mid); // if the minimum element in range [l, mid] // is less than arr[i], then mid can be // answer, we mark it, and look for a better // answer in left half. Else if q is greater // than arr[i], mid can't be an answer, we // should search in right half if (q < arr[i]) { ans = arr[mid]; r = mid - 1; } else { l = mid + 1; } } // print NSE for arr[i] Console.WriteLine(arr[i] + " ---> " + ans); } } static public void Main() { // Code int [] arr = { 11, 13, 21, 3 }; printNSE(arr, 4); } } // This code is contributed by lokeshmvs21. |
Javascript
// Program to find next smaller element for all elements in // an array, using segment tree and binary search // combine function for combining two nodes of the tree, in // this case we need to take min of two function combine(a, b) { return Math.min(a, b); } // build function, builds seg_tree // based on vector parameter arr function build(arr, node, tl, tr) { // if current range consists only of one element, then // node should be this element if (tl === tr) { seg_tree[node] = arr[tl]; } else { // divide the build operations into two parts var tm = Math.floor((tr - tl) / 2 + tl); build(arr, 2 * node, tl, tm); build(arr, 2 * node + 1, tm + 1, tr); // combine the results from two parts, and store it // into current node seg_tree[node] = combine(seg_tree[2 * node], seg_tree[2 * node + 1]); } } // query function, returns minimum in the range [l, r] function query(node, tl, tr, l, r) { // if range is invalid, then return infinity if (l > r) { return Number.MAX_SAFE_INTEGER; } // if range completely aligns with a segment tree node, // then value of this node should be returned if (l === tl && r === tr) { return seg_tree[node]; } // else divide the query into two parts var tm = Math.floor((tr - tl) / 2 + tl); var q1 = query(2 * node, tl, tm, l, Math.min(r, tm)); var q2 = query(2 * node + 1, tm + 1, tr, Math.max(l, tm + 1), r); // and combine the results from the // two parts and return it return combine(q1, q2); } // --------Segment Tree Ends Here----------------- function printNSE(arr, n) { seg_tree = new Array(4 * n); // build segment tree initially build(arr, 1, 0, n - 1); var q, l, r, mid, ans; for ( var i = 0; i < n; i++) { // binary search for ans in range [i + 1, n - 1], // initially ans is -1 representing there is no NSE // for this element l = i + 1; r = n - 1; ans = -1; while (l <= r) { mid = Math.floor((r - l) / 2 + l); // q is the minimum element in range [l, mid] q = query(1, 0, n - 1, l, mid); // if the minimum element in range [l, mid] is // less than arr[i], then mid can be answer, we // mark it, and look for a better answer in left // half. Else if q is greater than arr[i], mid // can't be an answer, we should search in right // half if (q < arr[i]) { ans = arr[mid]; r = mid - 1; } else { l = mid + 1; } } // print NSE for arr[i] console.log(arr[i] + " ---> " + ans); } } // Driver program to test above functions var arr = [11, 13, 21, 3]; printNSE(arr, 4); // This code is contributed by Akash Bankar (thebeginner01) |
11 ---> 3 13 ---> 3 21 ---> 3 3 ---> -1
Time Complexity :
For each of
array elements we do a binary search, which includes
steps, and each step costs
operations [range minimum queries].
Auxiliary Space: O(N)
As extra space is used for storing the elements of the segment tree.
Method 3 (Using Segment Tree and Coordinate Compression)
In this approach, we build a segment tree on indices of compressed array elements:
- Somewhere along the lines, we would build a array
such-that
is the smallest index at which
is present in input array.
- Its easy to see that we need to compress the input array so as to build this array
because if
exceeds
(memory limit of online judge) chances are we would get a segmentation fault.
- To compress we sort the input array, and then for each new value seen in array we map it to a corresponding smaller value, if possible. Use these mapped values to generate a
array with same order as input array.
- So now that we are done with compression, we can begin with the query part:
- Suppose in previous step, we compressed the array to
distinct values. Initially set
, this signifies no value is processed at any index as of now.
- Traverse the compressed array in reverse order, this would imply that in past we would have only processed elements that are on the right side.
- For
, query (and store in
) the smallest index of values
using segment tree, this must be the NSE for
!
- Update the index of
to
.
- For
- Suppose in previous step, we compressed the array to
- We stored the index of NSEs for all array elements, we can easily print NSEs themselves as shown in code.
Note: In implementation we use INT32_MAX instead of -1 because storing INT32_MAX doesn’t affect our min-segment tree and still serves the purpose of identifying unprocessed values.
As extra space is used for storing the elements of the segment tree.
C++
#include <bits/stdc++.h> using namespace std; // Program to find next smaller element for all elements in // an array, using segment tree and coordinate compression // --------Segment Tree Starts Here----------------- vector< int > seg_tree; // combine function for combining two nodes of the tree, in // this case we need to take min of two int combine( int a, int b) { return min(a, b); } // build function, builds seg_tree based on vector parameter // arr void build(vector< int >& arr, int node, int tl, int tr) { // if current range consists only of one element, then // node should be this element if (tl == tr) { seg_tree[node] = arr[tl]; } else { // divide the build operations into two parts int tm = (tr - tl) / 2 + tl; build(arr, 2 * node, tl, tm ); build(arr, 2 * node + 1, tm + 1, tr); // combine the results from two parts, and store it // into current node seg_tree[node] = combine(seg_tree[2 * node], seg_tree[2 * node + 1]); } } // update function, used to make a point update, update // arr[pos] to new_val and make required changes to segtree void update( int node, int tl, int tr, int pos, int new_val) { // if current range only contains one point, this must // be arr[pos], update the corresponding node to new_val if (tl == tr) { seg_tree[node] = new_val; } else { // else divide the range into two parts int tm = (tr - tl) / 2 + tl; // if pos lies in first half, update this half, else // update second half if (pos <= tm ) { update(2 * node, tl, tm , pos, new_val); } else { update(2 * node + 1, tm + 1, tr, pos, new_val); } // combine results from both halves seg_tree[node] = combine(seg_tree[2 * node], seg_tree[2 * node + 1]); } } // query function, returns minimum in the range [l, r] int query( int node, int tl, int tr, int l, int r) { // if range is invalid, then return infinity if (l > r) { return INT32_MAX; } // if range completely aligns with a segment tree node, // then value of this node should be returned if (l == tl && r == tr) { return seg_tree[node]; } // else divide the query into two parts int tm = (tr - tl) / 2 + tl; int q1 = query(2 * node, tl, tm , l, min(r, tm )); int q2 = query(2 * node + 1, tm + 1, tr, max(l, tm + 1), r); // and combine the results from the two parts and return // it return combine(q1, q2); } // --------Segment Tree Ends Here----------------- void printNSE(vector< int > original, int n) { vector< int > sorted(n); map< int , int > encode; // -------Coordinate Compression Starts Here ------ // created a temporary sorted array out of original for ( int i = 0; i < n; i++) { sorted[i] = original[i]; } sort(sorted.begin(), sorted.end()); // encode each value to a new value in sorted array int ctr = 0; for ( int i = 0; i < n; i++) { if (encode.count(sorted[i]) == 0) { encode[sorted[i]] = ctr++; } } // use encode to compress original array vector< int > compressed(n); for ( int i = 0; i < n; i++) { compressed[i] = encode[original[i]]; } // -------Coordinate Compression Ends Here ------ // Create an aux array of size ctr, and build a segtree // based on this array vector< int > aux(ctr, INT32_MAX); seg_tree = vector< int >(4 * ctr); build(aux, 1, 0, ctr - 1); // For each compressed[i], query for index of NSE and // update segment tree vector< int > ans(n); for ( int i = n - 1; i >= 0; i--) { ans[i] = query(1, 0, ctr - 1, 0, compressed[i] - 1); update(1, 0, ctr - 1, compressed[i], i); } // Print -1 if NSE doesn't exist, otherwise print NSE // itself for ( int i = 0; i < n; i++) { cout << original[i] << " ---> " ; if (ans[i] == INT32_MAX) { cout << -1; } else { cout << original[ans[i]]; } cout << "\n" ; } } // Driver program to test above functions int main() { vector< int > arr = { 11, 13, 21, 3 }; printNSE(arr, 4); return 0; } |
Java
// Java code to implement the above approach import java.io.*; import java.util.*; class GFG { // Program to find next smaller element for all elements // in // an array, using segment tree and coordinate // compression // --------Segment Tree Starts Here----------------- static int [] seg_tree; // combine function for combining two nodes of the tree, // in // this case we need to take min of two static int combine( int a, int b) { return Math.min(a, b); } // build function, builds seg_tree based on vector // parameter // arr static void build( int [] arr, int node, int tl, int tr) { // if current range consists only of one element, // then // node should be this element if (tl == tr) { seg_tree[node] = arr[tl]; } else { // divide the build operations into two parts int tm = (tr - tl) / 2 + tl; build(arr, 2 * node, tl, tm); build(arr, 2 * node + 1 , tm + 1 , tr); // combine the results from two parts, and store // it into current node seg_tree[node] = combine( seg_tree[ 2 * node], seg_tree[ 2 * node + 1 ]); } } // update function, used to make a point update, update // arr[pos] to new_val and make required changes to // segtree static void update( int node, int tl, int tr, int pos, int new_val) { // if current range only contains one point, this // must // be arr[pos], update the corresponding node to // new_val if (tl == tr) { seg_tree[node] = new_val; } else { // else divide the range into two parts int tm = (tr - tl) / 2 + tl; // if pos lies in first half, update this half, // else update second half if (pos <= tm) { update( 2 * node, tl, tm, pos, new_val); } else { update( 2 * node + 1 , tm + 1 , tr, pos, new_val); } // combine results from both halves seg_tree[node] = combine( seg_tree[ 2 * node], seg_tree[ 2 * node + 1 ]); } } // query function, returns minimum in the range [l, r] static int query( int node, int tl, int tr, int l, int r) { // if range is invalid, then return infinity if (l > r) { return Integer.MAX_VALUE; } // if range completely aligns with a segment tree // node, // then value of this node should be returned if (l == tl && r == tr) { return seg_tree[node]; } // else divide the query into two parts int tm = (tr - tl) / 2 + tl; int q1 = query( 2 * node, tl, tm, l, Math.min(r, tm)); int q2 = query( 2 * node + 1 , tm + 1 , tr, Math.max(l, tm + 1 ), r); // and combine the results from the two parts and // return it return combine(q1, q2); } // --------Segment Tree Ends Here----------------- static void printNSE( int [] original, int n) { int [] sorted = new int [n]; HashMap<Integer, Integer> encode = new HashMap<>(); // -------Coordinate Compression Starts Here ------ // created a temporary sorted array out of original for ( int i = 0 ; i < n; i++) { sorted[i] = original[i]; } Arrays.sort(sorted); // encode each value to a new value in sorted array int ctr = 0 ; for ( int i = 0 ; i < n; i++) { if (!encode.containsKey(sorted[i])) { encode.put(sorted[i], ctr++); } } // use encode to compress original array int [] compressed = new int [n]; for ( int i = 0 ; i < n; i++) { compressed[i] = encode.get(original[i]); } // -------Coordinate Compression Ends Here ------ // Create an aux array of size ctr, and build a // segtree based on this array int [] aux = new int [ctr]; for ( int i = 0 ; i < ctr; i++) { aux[i] = Integer.MAX_VALUE; } seg_tree = new int [ 4 * ctr]; build(aux, 1 , 0 , ctr - 1 ); // For each compressed[i], query for index of NSE // and // update segment tree int [] ans = new int [n]; for ( int i = n - 1 ; i >= 0 ; i--) { ans[i] = query( 1 , 0 , ctr - 1 , 0 , compressed[i] - 1 ); update( 1 , 0 , ctr - 1 , compressed[i], i); } // Print -1 if NSE doesn't exist, otherwise print // NSE // itself for ( int i = 0 ; i < n; i++) { System.out.print(original[i] + " ---> " ); if (ans[i] == Integer.MAX_VALUE) { System.out.println(- 1 ); } else { System.out.println(original[ans[i]]); } } } public static void main(String[] args) { int [] arr = { 11 , 13 , 21 , 3 }; printNSE(arr, 4 ); } } // This code is contributed by lokesh. |
C#
// C# code to implement the above approach using System; using System.Collections; using System.Collections.Generic; public class GFG { // Program to find next smaller element for all elements // in an array, using segment tree and coordinate // compression // --------Segment Tree Starts Here----------------- static int [] seg_tree; // combine function for combining two nodes of the tree, // in this case we need to take min of two static int combine( int a, int b) { return Math.Min(a, b); } // build function, builds seg_tree based on vector // parameter arr static void build( int [] arr, int node, int tl, int tr) { // if current range consists only of one element, // then node should be this element if (tl == tr) { seg_tree[node] = arr[tl]; } else { // divide the build operations into two parts int tm = (tr - tl) / 2 + tl; build(arr, 2 * node, tl, tm); build(arr, 2 * node + 1, tm + 1, tr); // combine the results from two parts, and store // it into current node seg_tree[node] = combine( seg_tree[2 * node], seg_tree[2 * node + 1]); } } // update function, used to make a point update, update // arr[pos] to new_val and make required changes to // segtree static void update( int node, int tl, int tr, int pos, int new_val) { // if current range only contains one point, this // must be arr[pos], update the corresponding node // to new_val if (tl == tr) { seg_tree[node] = new_val; } else { // else divide the range into two parts int tm = (tr - tl) / 2 + tl; // if pos lies in first half, update this half, // else update second half if (pos <= tm) { update(2 * node, tl, tm, pos, new_val); } else { update(2 * node + 1, tm + 1, tr, pos, new_val); } // combine results from both halves seg_tree[node] = combine( seg_tree[2 * node], seg_tree[2 * node + 1]); } } // query function, returns minimum in the range [l, r] static int query( int node, int tl, int tr, int l, int r) { // if range is invalid, then return infinity if (l > r) { return Int32.MaxValue; } // if range completely aligns with a segment tree // node, then value of this node should be returned if (l == tl && r == tr) { return seg_tree[node]; } // else divide the query into two parts int tm = (tr - tl) / 2 + tl; int q1 = query(2 * node, tl, tm, l, Math.Min(r, tm)); int q2 = query(2 * node + 1, tm + 1, tr, Math.Max(l, tm + 1), r); // and combine the results from the two parts and // return it return combine(q1, q2); } // --------Segment Tree Ends Here----------------- static void printNSE( int [] original, int n) { int [] sorted = new int [n]; Dictionary< int , int > encode = new Dictionary< int , int >(); // -------Coordinate Compression Starts Here ------ // created a temporary sorted array out of original for ( int i = 0; i < n; i++) { sorted[i] = original[i]; } Array.Sort(sorted); // encode each value to a new value in sorted array int ctr = 0; for ( int i = 0; i < n; i++) { if (!encode.ContainsKey(sorted[i])) { encode.Add(sorted[i], ctr++); } } // use encode to compress original array int [] compressed = new int [n]; for ( int i = 0; i < n; i++) { compressed[i] = encode[original[i]]; } // -------Coordinate Compression Ends Here ------ // Create an aux array of size ctr, and build a // segtree based on this array int [] aux = new int [ctr]; for ( int i = 0; i < ctr; i++) { aux[i] = Int32.MaxValue; } seg_tree = new int [4 * ctr]; build(aux, 1, 0, ctr - 1); // For each compressed[i], query for index of NSE // and update segment tree int [] ans = new int [n]; for ( int i = n - 1; i >= 0; i--) { ans[i] = query(1, 0, ctr - 1, 0, compressed[i] - 1); update(1, 0, ctr - 1, compressed[i], i); } // Print -1 if NSE doesn't exist, otherwise print // NSE itself for ( int i = 0; i < n; i++) { Console.Write(original[i] + " ---> " ); if (ans[i] == Int32.MaxValue) { Console.WriteLine(-1); } else { Console.WriteLine(original[ans[i]]); } } } static public void Main() { // Code int [] arr = { 11, 13, 21, 3 }; printNSE(arr, 4); } } // This code is contributed by lokesh. |
Python3
# Program to find next smaller element for all elements in # an array, using segment tree and coordinate compression # --------Segment Tree Starts Here----------------- seg_tree = [] # combine function for combining two nodes of the tree, in # this case we need to take min of two def combine(a, b): return min (a, b) # build function, builds seg_tree based on vector parameter # arr def build(arr, node, tl, tr): # if current range consists only of one element, then # node should be this element if tl = = tr: seg_tree[node] = arr[tl] else : # divide the build operations into two parts tm = (tr - tl) / / 2 + tl build(arr, 2 * node, tl, tm) build(arr, 2 * node + 1 , tm + 1 , tr) # combine the results from two parts, and store it # into current node seg_tree[node] = combine(seg_tree[ 2 * node], seg_tree[ 2 * node + 1 ]) # update function, used to make a point update, update # arr[pos] to new_val and make required changes to segtree def update(node, tl, tr, pos, new_val): # if current range only contains one point, this must # be arr[pos], update the corresponding node to new_val if tl = = tr: seg_tree[node] = new_val else : # else divide the range into two parts tm = (tr - tl) / / 2 + tl # if pos lies in first half, update this half, else # update second half if pos < = tm: update( 2 * node, tl, tm, pos, new_val) else : update( 2 * node + 1 , tm + 1 , tr, pos, new_val) # combine results from both halves seg_tree[node] = combine(seg_tree[ 2 * node], seg_tree[ 2 * node + 1 ]) # query function, returns minimum in the range [l, r] def query(node, tl, tr, l, r): # if range is invalid, then return infinity if l > r: return float ( "inf" ) # if range completely aligns with a segment tree node, # then value of this node should be returned if l = = tl and r = = tr: return seg_tree[node] # else divide the query into two parts tm = (tr - tl) / / 2 + tl q1 = query( 2 * node, tl, tm, l, min (r, tm)) q2 = query( 2 * node + 1 , tm + 1 , tr, max (l, tm + 1 ), r) # and combine the results from the two parts and return # it return combine(q1, q2) # --------Segment Tree Ends Here----------------- def printNSE(original, n): sorted = [ 0 ] * n encode = {} # -------Coordinate Compression Starts Here ------ # created a temporary sorted array out of original for i in range (n): sorted [i] = original[i] sorted .sort() # encode each value to a new value in sorted array ctr = 0 for i in range (n): if sorted [i] not in encode.keys(): encode[ sorted [i]] = ctr ctr + = 1 # use encode to compress original array compressed = [ 0 ] * n for i in range (n): compressed[i] = encode[original[i]] # -------Coordinate Compression Ends Here ------ # Create an aux array of size ctr, and build a segtree # based on this array aux = [ float ( "inf" )] * ctr seg_tree[:] = [ float ( "inf" )] * 4 * ctr build(aux, 1 , 0 , ctr - 1 ) # For each compressed[i], query for index of NSE and # update segment tree ans = [ 0 ] * n for i in range (n - 1 , - 1 , - 1 ): ans[i] = query( 1 , 0 , ctr - 1 , 0 , compressed[i] - 1 ) update( 1 , 0 , ctr - 1 , compressed[i], i) # Print -1 if NSE doesn't exist, otherwise print NSE # itself for i in range (n): print (original[i], " ---> " , end = "") if ans[i] = = float ( "inf" ): print ( - 1 , end = "") else : print (original[ans[i]], end = "") print () # Driver program to test above functions if __name__ = = '__main__' : arr = [ 11 , 13 , 21 , 3 ] printNSE(arr, 4 ) |
Javascript
// Program to find next smaller element for all elements in // an array, using segment tree and coordinate compression // --------Segment Tree Starts Here----------------- let seg_tree = []; // combine function for combining two nodes of the tree, in // this case we need to take min of two function combine(a, b) { return Math.min(a, b); } // build function, builds seg_tree based on vector parameter // arr function build(arr, node, tl, tr) { // if current range consists only of one element, then // node should be this element if (tl === tr) { seg_tree[node] = arr[tl]; } else { // divide the build operations into two parts let tm = Math.floor((tr - tl)/2) + tl; build(arr, 2 * node, tl, tm); build(arr, 2 * node + 1, tm + 1, tr); // combine the results from two parts, and store it // into current node seg_tree[node] = combine(seg_tree[2 * node], seg_tree[2 * node + 1]); } } // update function, used to make a point update, update // arr[pos] to new_val and make required changes to segtree function update(node, tl, tr, pos, new_val) { // if current range only contains one point, this must // be arr[pos], update the corresponding node to new_val if (tl === tr) { seg_tree[node] = new_val; } else { // else divide the range into two parts let tm = Math.floor((tr - tl)/2) + tl; // if pos lies in first half, update this half, else // update second half if (pos <= tm) { update(2 * node, tl, tm, pos, new_val); } else { update(2 * node + 1, tm + 1, tr, pos, new_val); } // combine results from both halves seg_tree[node] = combine(seg_tree[2 * node], seg_tree[2 * node + 1]); } } // query function, returns minimum in the range [l, r] function query(node, tl, tr, l, r) { // if range is invalid, then return infinity if (l > r) { return Number.POSITIVE_INFINITY; } // if range completely aligns with a segment tree node, // then value of this node should be returned if (l === tl && r === tr) { return seg_tree[node]; } // else divide the query into two parts let tm = Math.floor((tr - tl)/2) + tl; let q1 = query(2 * node, tl, tm, l, Math.min(r, tm)); let q2 = query(2 * node + 1, tm + 1, tr, Math.max(l, tm + 1), r); // and combine the results from the two parts and return // it return combine(q1, q2); } // --------Segment Tree Ends Here----------------- function printNSE(original, n) { let sorted = Array(n).fill(0); let encode = {}; // -------Coordinate Compression Starts Here ------ // created a temporary sorted array out of original for (let i = 0; i < n; i++) { sorted[i] = original[i]; } sorted.sort( function (a, b){ return a-b}); // encode each value to a new value in sorted array let ctr = 0; for (let i = 0; i < n; i++) { if (!encode.hasOwnProperty(sorted[i])) { encode[sorted[i]] = ctr; ctr += 1; } } // use encode to compress original array let compressed = Array(n).fill(0); for (let i = 0; i < n; i++) { compressed[i] = encode[original[i]]; } // -------Coordinate Compression Ends Here ------ // Create an aux array of size ctr, and build a segtree // based on this array let aux = Array(ctr).fill(Number.POSITIVE_INFINITY); seg_tree.fill(Number.POSITIVE_INFINITY); build(aux, 1, 0, ctr - 1); // For each compressed[i], query for index of NSE and // update segment tree let ans = Array(n).fill(0); for (let i = n-1; i >= 0; i--) { ans[i] = query(1, 0, ctr - 1, 0, compressed[i] - 1); update(1, 0, ctr - 1, compressed[i], i); } // Print -1 if NSE doesn't exist, otherwise print NSE // itself for (let i = 0; i < n; i++) { if (ans[i] === Number.POSITIVE_INFINITY) { console.log(original[i], " ---> " , -1); } else { console.log(original[i], " ---> " , original[ans[i]]); } } } // Driver program to test above functions //if (require.main === module) { let arr = [11, 13, 21, 3]; printNSE(arr, 4); //} // This code is contributed by akashish__ |
11 ---> 3 13 ---> 3 21 ---> 3 3 ---> -1
Time Complexity:
![]()
Auxiliary Space: O(N)
Method 4 (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).
- Push the first element to stack.
- Pick rest of 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. next becomes the NSE for all such popped elements
- Push next into the stack
- After the loop in step 2 is over, pop all the elements from stack and print -1 as next element for them.
Note: To achieve the same order, we use a stack of pairs, where first element is the value and second element is index of array element.
C++
// A Stack based C++ program to find next // smaller element for all array elements #include <bits/stdc++.h> using namespace std; // prints NSE for elements of array arr[] of size n void printNSE( int arr[], int n) { stack<pair< int , int > > s; vector< int > ans(n); // iterate for rest of the elements for ( int i = 0; i < n; i++) { int next = arr[i]; // if stack is empty then this element can't be NSE // for any other element, so just push it to stack // so that we can find NSE for it, and continue if (s.empty()) { s.push({ next, i }); continue ; } // while stack is not empty and the top element is // greater than next // a) NSE for top is next, use top's index to // maintain original order // b) pop the top element from stack while (!s.empty() && s.top().first > next) { ans[s.top().second] = next; s.pop(); } // push next to stack so that we can find NSE for it s.push({ next, i }); } // After iterating over the loop, the remaining elements // in stack do not have any NSE, so set -1 for them while (!s.empty()) { ans[s.top().second] = -1; s.pop(); } for ( int i = 0; i < n; i++) { cout << arr[i] << " ---> " << ans[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.io.*; import java.lang.*; import java.util.*; 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> |
11 ---> 3 13 ---> 3 21 ---> 3 3 ---> -1
Time Complexity:
As we use only single for loop and all the elements in the stack are push and popped atmost once.
Auxiliary Space: O(N)
As extra space is used for storing the elements of the stack.
Please Login to comment...