Open In App

Find next Smaller of next Greater in an array

Last Updated : 05 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given array of integer, find the next smaller of next greater element of every element in array.

Note : Elements for which no greater element exists or no smaller of greater element exist, print -1.

Examples: 

Input : arr[] = {5, 1, 9, 2, 5, 1, 7}
Output:          2  2 -1  1 -1 -1 -1
Explanation :  
Next Greater ->      Right Smaller 
   5 ->  9             9 ->  2 
   1 ->  9             9 ->  2
   9 -> -1            -1 -> -1
   2 ->  5             5 ->  1
   5 ->  7             7 -> -1
   1 ->  7             7 -> -1
   7 -> -1            -1 -> -1 

Input  : arr[] = {4, 8, 2, 1, 9, 5, 6, 3}
Output :          2  5  5  5 -1  3 -1 -1                    

A simple solution is to iterate through all elements. For every element, find the next greater element of current element and then find right smaller element for current next greater element. 

Code-

C++




// C++ Program to find Right smaller element of next
// greater element
#include<bits/stdc++.h>
using namespace std;
 
// Function to find Right smaller element of next greater
// element
void nextSmallerOfNextGreater(int arr[], int n)
{
    vector<int> vec;
    //For 1st n-1 elements of vector
    for(int i=0;i<n-1;i++){
        
        int temp=arr[i];
        int next=-1;
        int ans=-1;
        for(int j=i+1;j<n;j++){
          if(arr[j]>temp){
              next=j;
              break;
          }
        }
          
        if(next==-1){vec.push_back(-1);}
        else{
          for(int j=next+1;j<n;j++){
              if(arr[j]<arr[next]){
                  ans=j;
                  break;
              }
          }
          if(ans==-1){vec.push_back(-1);}
          else{vec.push_back(arr[ans]);}
        }
         
    }
     
    vec.push_back(-1);//For last element of vector
    for(auto x: vec){
        cout<<x<<" ";
    }
    cout<<endl;
}
 
// Driver program
int main()
{
    int arr[] = {5, 1, 9, 2, 5, 1, 7};
    int n = sizeof(arr)/sizeof(arr[0]);
    nextSmallerOfNextGreater(arr, n);
    return 0;
}


Java




// Java Program to find Right smaller element of next
// greater element
import java.util.*;
 
public class Main {
 
  // Function to find Right smaller element of next greater element
  static void nextSmallerOfNextGreater(int arr[], int n) {
    ArrayList<Integer> vec = new ArrayList<Integer>();
 
    // For 1st n-1 elements of vector
    for(int i = 0; i < n - 1; i++) {
      int temp = arr[i];
      int next = -1;
      int ans = -1;
      for(int j = i + 1; j < n; j++) {
        if(arr[j] > temp) {
          next = j;
          break;
        }
      }
      if(next == -1) {
        vec.add(-1);
      }
      else {
        for(int j = next + 1; j < n; j++) {
          if(arr[j] < arr[next]) {
            ans = j;
            break;
          }
        }
        if(ans == -1) {
          vec.add(-1);
        }
        else {
          vec.add(arr[ans]);
        }
      }
    }
    vec.add(-1); // For last element of vector
 
    for(int x : vec) {
      System.out.print(x + " ");
    }
    System.out.println();
  }
 
  // Driver program
  public static void main(String[] args) {
    int arr[] = {5, 1, 9, 2, 5, 1, 7};
    int n = arr.length;
    nextSmallerOfNextGreater(arr, n);
  }
}


Python3




# Function to find Right smaller element of next greater element
def nextSmallerOfNextGreater(arr, n):
    vec = []
    # For 1st n-1 elements of vector
    for i in range(n-1):
        temp = arr[i]
        next = -1
        ans = -1
        for j in range(i+1, n):
            if arr[j] > temp:
                next = j
                break
        if next == -1:
            vec.append(-1)
        else:
            for j in range(next+1, n):
                if arr[j] < arr[next]:
                    ans = j
                    break
            if ans == -1:
                vec.append(-1)
            else:
                vec.append(arr[ans])
    vec.append(-1# For last element of vector
    for x in vec:
        print(x, end=" ")
    print()
 
 
# Driver program
arr = [5, 1, 9, 2, 5, 1, 7]
n = len(arr)
nextSmallerOfNextGreater(arr, n)


C#




using System;
using System.Collections.Generic;
 
public class MainClass
{
 
  // Function to find Right smaller element of next
  // greater element
  static void nextSmallerOfNextGreater(int[] arr, int n)
  {
    List<int> vec = new List<int>();
 
    // For 1st n-1 elements of vector
    for (int i = 0; i < n - 1; i++) {
 
      int temp = arr[i];
      int next = -1;
      int ans = -1;
      for (int j = i + 1; j < n; j++) {
        if (arr[j] > temp) {
          next = j;
          break;
        }
      }
 
      if (next == -1) {
        vec.Add(-1);
      }
      else {
        for (int j = next + 1; j < n; j++) {
          if (arr[j] < arr[next]) {
            ans = j;
            break;
          }
        }
        if (ans == -1) {
          vec.Add(-1);
        }
        else {
          vec.Add(arr[ans]);
        }
      }
    }
 
    vec.Add(-1); // For last element of vector
    foreach(var x in vec) { Console.Write(x + " "); }
    Console.WriteLine();
  }
 
  // Driver program
  public static void Main()
  {
    int[] arr = { 5, 1, 9, 2, 5, 1, 7 };
    int n = arr.Length;
    nextSmallerOfNextGreater(arr, n);
  }
}


Javascript




// Function to find Right smaller element of next greater element
function nextSmallerOfNextGreater(arr, n) {
  let vec = [];
  // For 1st n-1 elements of vector
  for (let i = 0; i < n - 1; i++) {
    let temp = arr[i];
    let next = -1;
    let ans = -1;
    for (let j = i + 1; j < n; j++) {
      if (arr[j] > temp) {
        next = j;
        break;
      }
    }
    if (next == -1) {
      vec.push(-1);
    } else {
      for (let j = next + 1; j < n; j++) {
        if (arr[j] < arr[next]) {
          ans = j;
          break;
        }
      }
      if (ans == -1) {
        vec.push(-1);
      } else {
        vec.push(arr[ans]);
      }
    }
  }
  vec.push(-1); // For last element of vector
  for (let x of vec) {
    process.stdout.write(x + " ");
  }
  console.log();
}
 
// Driver program
let arr = [5, 1, 9, 2, 5, 1, 7];
let n = arr.length;
nextSmallerOfNextGreater(arr, n);


Output

2 2 -1 1 -1 -1 -1 

Time Complexity of this solution is O(n2).

Space Complexity: O(1) 

An efficient solution takes O(n) time. Notice that it is the combination of Next greater element & next smaller element in array.

Let input array be 'arr[]' and size of array be 'n'
find next greatest element of every element 

 step 1 : Create an empty stack (S) in which we store the indexes
          and NG[] that is user to store the indexes of NGE
          of every element.

 step 2 : Traverse the array in reverse order 
            where i goes from (n-1 to 0)

        a) While S is non empty and the top element of 
           S is smaller than or equal to 'arr[i]':
              pop S

        b) If S is empty 
             arr[i] has no greater element
             NG[i] = -1

        c) else we have next greater element
             NG[i] = S.top() // here we store the index of NGE

        d) push current element index in stack 
           S.push(i)

Find Right smaller element of every element      
    
  step 3 : create an array RS[] used to store the index of
           right smallest element 

  step 4 : we repeat step (1 & 2)  with little bit of
           modification in step 1 & 2 .
           they are :

          a). we use RS[] in place of NG[].

          b). In step (2.a)
              we pop element form stack S  while S is not
              empty or the top element of S is greater than 
              or equal to 'arr[i]'  

  step 5 : compute all RSE of NGE :

           where i goes from 0 to n-1 
          if NG[ i ] != -1 && RS[ NG [ i]] ! =-1
              print arr[RS[NG[i]]]
          else
              print -1                

Below is the implementation of above idea

C++




// C++ Program to find Right smaller element of next
// greater element
#include<bits/stdc++.h>
using namespace std;
 
// function find Next greater element
void nextGreater(int arr[], int n, int next[], char order)
{
    // create empty stack
    stack<int> S;
 
    // Traverse all array elements in reverse order
    // order == 'G' we compute next greater elements of
    //              every element
    // order == 'S' we compute right smaller element of
    //              every element
    for (int i=n-1; i>=0; i--)
    {
        // Keep removing top element from S while the top
        // element is smaller than or equal to arr[i] (if Key is G)
        // element is greater than or equal to arr[i] (if order is S)
        while (!S.empty() &&
              ((order=='G')? arr[S.top()] <= arr[i]:
                           arr[S.top()] >= arr[i]))
            S.pop();
 
        // store the next greater element of current element
        if (!S.empty())
            next[i] = S.top();
 
        // If all elements in S were smaller than arr[i]
        else
            next[i] = -1;
 
        // Push this element
        S.push(i);
    }
}
 
// Function to find Right smaller element of next greater
// element
void nextSmallerOfNextGreater(int arr[], int n)
{
    int NG[n]; // stores indexes of next greater elements
    int RS[n]; // stores indexes of right smaller elements
 
    // Find next greater element
    // Here G indicate next greater element
    nextGreater(arr, n, NG, 'G');
 
    // Find right smaller element
    // using same function nextGreater()
    // Here S indicate right smaller elements
    nextGreater(arr, n, RS, 'S');
 
    // If NG[i] == -1 then there is no smaller element
    // on right side. We can find Right smaller of next
    // greater by arr[RS[NG[i]]]
    for (int i=0; i< n; i++)
    {
        if (NG[i] != -1 && RS[NG[i]] != -1)
            cout << arr[RS[NG[i]]] << " ";
        else
            cout<<"-1"<<" ";
    }
}
 
// Driver program
int main()
{
    int arr[] = {5, 1, 9, 2, 5, 1, 7};
    int n = sizeof(arr)/sizeof(arr[0]);
    nextSmallerOfNextGreater(arr, n);
    return 0;
}


Java




// Java Program to find Right smaller element of next
// greater element
import java.util.Stack;
public class Main {
    // function find Next greater element
    public static void nextGreater(int arr[], int next[], char order)
    {
        // create empty stack
        Stack<Integer> stack=new Stack<>();
   
        // Traverse all array elements in reverse order
        // order == 'G' we compute next greater elements of
        //              every element
        // order == 'S' we compute right smaller element of
        //              every element
        for (int i=arr.length-1; i>=0; i--)
        {
            // Keep removing top element from S while the top
            // element is smaller than or equal to arr[i] (if Key is G)
            // element is greater than or equal to arr[i] (if order is S)
            while (!stack.isEmpty() && ((order=='G')? arr[stack.peek()] <= arr[i]:arr[stack.peek()] >= arr[i]))
                stack.pop();
   
            // store the next greater element of current element
            if (!stack.isEmpty())
                next[i] = stack.peek();
   
            // If all elements in S were smaller than arr[i]
            else
                next[i] = -1;
   
            // Push this element
            stack.push(i);
        }
    }
 
    // Function to find Right smaller element of next greater
    // element
    public static void nextSmallerOfNextGreater(int arr[])
    {
        int NG[]=new int[arr.length]; // stores indexes of next greater elements
        int RS[]=new int[arr.length]; // stores indexes of right smaller elements
   
        // Find next greater element
        // Here G indicate next greater element
        nextGreater(arr, NG, 'G');
   
        // Find right smaller element
        // using same function nextGreater()
        // Here S indicate right smaller elements
        nextGreater(arr, RS, 'S');
   
        // If NG[i] == -1 then there is no smaller element
        // on right side. We can find Right smaller of next
        // greater by arr[RS[NG[i]]]
        for (int i=0; i< arr.length; i++)
        {
            if (NG[i] != -1 && RS[NG[i]] != -1)
                System.out.print(arr[RS[NG[i]]]+" ");
            else
                System.out.print("-1 ");
        }
    
 
    public static void main(String args[]) {
        int arr[] = {5, 1, 9, 2, 5, 1, 7}; 
        nextSmallerOfNextGreater(arr);
    }
}
//This code is contributed by Gaurav Tiwari


Python 3




# Python 3 Program to find Right smaller element of next
# greater element
  
# function find Next greater element
def nextGreater(arr, n, next, order):
 
    S = []
  
    # Traverse all array elements in reverse order
    # order == 'G' we compute next greater elements of
    #              every element
    # order == 'S' we compute right smaller element of
    #              every element
    for i in range(n-1,-1,-1):
 
        # Keep removing top element from S while the top
        # element is smaller than or equal to arr[i] (if Key is G)
        # element is greater than or equal to arr[i] (if order is S)
        while (S!=[] and (arr[S[len(S)-1]] <= arr[i]
        if (order=='G') else  arr[S[len(S)-1]] >= arr[i] )):
                
            S.pop()
  
        # store the next greater element of current element
        if (S!=[]):
            next[i] = S[len(S)-1]
  
        # If all elements in S were smaller than arr[i]
        else:
            next[i] = -1
  
        # Push this element
        S.append(i)
  
# Function to find Right smaller element of next greater
# element
def nextSmallerOfNextGreater(arr, n):
    NG = [None]*#  stores indexes of next greater elements
    RS = [None]*# stores indexes of right smaller elements
  
    # Find next greater element
    # Here G indicate next greater element
    nextGreater(arr, n, NG, 'G')
  
    # Find right smaller element
    # using same function nextGreater()
    # Here S indicate right smaller elements
    nextGreater(arr, n, RS, 'S')
  
    # If NG[i] == -1 then there is no smaller element
    # on right side. We can find Right smaller of next
    # greater by arr[RS[NG[i]]]
    for i in range(n):
        if (NG[i] != -1 and RS[NG[i]] != -1):
            print(arr[RS[NG[i]]],end=" ")
        else:
            print("-1",end=" ")
  
# Driver program
if __name__=="__main__":
    arr = [5, 1, 9, 2, 5, 1, 7]
    n = len(arr)
    nextSmallerOfNextGreater(arr, n)
 
# this code is contributed by ChitraNayal


C#




using System;
using System.Collections.Generic;
 
// C# Program to find Right smaller element of next
// greater element
public class GFG {
    // function find Next greater element
    public static void nextGreater(int []arr, int []next, char order)
    {
        // create empty stack
        Stack<int> stack=new Stack<int>();
     
        // Traverse all array elements in reverse order
        // order == 'G' we compute next greater elements of
        //             every element
        // order == 'S' we compute right smaller element of
        //             every element
        for (int i=arr.Length-1; i>=0; i--)
        {
            // Keep removing top element from S while the top
            // element is smaller than or equal to arr[i] (if Key is G)
            // element is greater than or equal to arr[i] (if order is S)
            while (stack.Count!=0 && ((order=='G')? arr[stack.Peek()] <= arr[i]:arr[stack.Peek()] >= arr[i]))
                stack.Pop();
     
            // store the next greater element of current element
            if (stack.Count!=0)
                next[i] = stack.Peek();
     
            // If all elements in S were smaller than arr[i]
            else
                next[i] = -1;
     
            // Push this element
            stack.Push(i);
        }
    }
 
    // Function to find Right smaller element of next greater
    // element
    public static void nextSmallerOfNextGreater(int []arr)
    {
        int []NG=new int[arr.Length]; // stores indexes of next greater elements
        int []RS=new int[arr.Length]; // stores indexes of right smaller elements
     
        // Find next greater element
        // Here G indicate next greater element
        nextGreater(arr, NG, 'G');
     
        // Find right smaller element
        // using same function nextGreater()
        // Here S indicate right smaller elements
        nextGreater(arr, RS, 'S');
     
        // If NG[i] == -1 then there is no smaller element
        // on right side. We can find Right smaller of next
        // greater by arr[RS[NG[i]]]
        for (int i=0; i< arr.Length; i++)
        {
            if (NG[i] != -1 && RS[NG[i]] != -1)
                Console.Write(arr[RS[NG[i]]]+" ");
            else
                Console.Write("-1 ");
        }
    }
 
    public static void Main() {
        int []arr = {5, 1, 9, 2, 5, 1, 7};
        nextSmallerOfNextGreater(arr);
    }
}
// This code is contributed by PrinciRaj1992


Javascript




<script>
// Javascript Program to find Right smaller element of next
// greater element
     
    // function find Next greater element
    function nextGreater(arr,next,order)
    {
     
        // create empty stack
        let stack = [];
         
        // Traverse all array elements in reverse order
        // order == 'G' we compute next greater elements of
        //              every element
        // order == 'S' we compute right smaller element of
        //              every element
        for (let i = arr.length - 1; i >= 0; i--)
        {
         
            // Keep removing top element from S while the top
            // element is smaller than or equal to arr[i] (if Key is G)
            // element is greater than or equal to arr[i] (if order is S)
            while (stack.length!=0 && ((order=='G')? arr[stack[stack.length-1]] <= arr[i] : arr[stack[stack.length-1]] >= arr[i]))
                stack.pop();
     
            // store the next greater element of current element
            if (stack.length != 0)
                next[i] = stack[stack.length - 1];
     
            // If all elements in S were smaller than arr[i]
            else
                next[i] = -1;
     
            // Push this element
            stack.push(i);
        }
    }
     
    // Function to find Right smaller element of next greater
    // element
    function nextSmallerOfNextGreater(arr)
    {
        let NG = new Array(arr.length); // stores indexes of next greater elements
        let RS = new Array(arr.length); // stores indexes of right smaller elements
        for(let i = 0; i < arr.length; i++)
        {
            NG[i] = 0;
            RS[i] = 0;
        }
         
        // Find next greater element
        // Here G indicate next greater element
        nextGreater(arr, NG, 'G');
     
        // Find right smaller element
        // using same function nextGreater()
        // Here S indicate right smaller elements
        nextGreater(arr, RS, 'S');
     
        // If NG[i] == -1 then there is no smaller element
        // on right side. We can find Right smaller of next
        // greater by arr[RS[NG[i]]]
        for (let i = 0; i < arr.length; i++)
        {
            if (NG[i] != -1 && RS[NG[i]] != -1)
                document.write(arr[RS[NG[i]]] + " ");
            else
                document.write("-1 ");
        }
    }
     
    // Driver code
    let arr = [5, 1, 9, 2, 5, 1, 7];
    nextSmallerOfNextGreater(arr);
     
    // This code is contributed by rag2127
</script>


Output

2 2 -1 1 -1 -1 -1 

Time complexity : O(n), where n is the size of the given array.
Auxiliary Space: O(n), where n is the size of the given array.



Previous Article
Next Article

Similar Reads

Delete Array Elements which are Smaller than Next or Become Smaller
Given an array arr[] and a number k. The task is to delete k elements which are smaller than next element (i.e., we delete arr[i] if arr[i] &lt; arr[i+1]) or become smaller than next because next element is deleted. Example: Input : arr[] = { 3, 100, 1 }, k = 1Output : 100, 1Explanation : arr[0] &lt; arr[1] means 3 is less than 100, so delete 3 Inp
10 min read
Closest (or Next) smaller and greater numbers with same number of set bits
Given a positive integer n, print the next smallest and the previous largest number that has the same number of 1 bit in their binary representation. Examples: Input : n = 5 Output : Closest Greater = 6 Closest Smaller = 3 Note that 5, 6 and 3 have same number of set bits. Input : n = 11 Output : Closest Greater = 13 Closest Smaller = 7 The Brute F
15+ min read
For all Array elements find Product of Sum of all smaller and Sum of all greater elements
Given an array arr[] of integers of length N, the task is to find the product of the sum of all the numbers larger than that number with the sum of all the numbers less than that number for each number in the array. Examples: Input: arr[] = {8, 4, 9, 3}, N = 4Output:- 63, 51, 0, 0Explanation:For first number 8: Sum of elements smaller than this is
15 min read
Find the element before which all the elements are smaller than it, and after which all are greater
Given an array, find an element before which all elements are smaller than it, and after which all are greater than it. Return the index of the element if there is such an element, otherwise, return -1. Examples: Input: arr[] = {5, 1, 4, 3, 6, 8, 10, 7, 9}; Output: 4 Explanation: All elements on left of arr[4] are smaller than it and all elements o
15+ min read
Size of smallest subarray to be removed to make count of array elements greater and smaller than K equal
Given an integer K and an array arr[] consisting of N integers, the task is to find the length of the subarray of smallest possible length to be removed such that the count of array elements smaller than and greater than K in the remaining array are equal. Examples: Input: arr[] = {5, 7, 2, 8, 7, 4, 5, 9}, K = 5Output: 2Explanation:Smallest subarra
10 min read
Minimize array sum by replacing greater and smaller elements of pairs by half and double of their values respectively atmost K times
Given an array arr[] consisting of N positive integers and an integer K, the task is to find the minimum possible array sum that can be obtained by repeatedly selecting a pair from the given array and divide one of the elements by 2 and multiply the other element by 2, at most K times. Examples: Input: arr[] = {5, 1, 10, 2, 3}, K = 1 Output: 17 Exp
15+ min read
Modify Array such that no element is smaller/greater than half/double of its adjacent elements
Given an array, arr[] of size N. Find the minimum number of elements we need to insert between array elements such that the maximum element from two adjacent elements is not more than twice bigger than the minimum element i.e., max(arr[i], arr[i+1]) ? 2 * min(arr[i], arr[i+1]) where 0 ? i &lt; N - 1. Examples: Input: N = 5, A[] = {1, 2, 3, 4, 3}Out
7 min read
Count elements in Array having strictly smaller and strictly greater element present
Given an array arr[], the task is to find the count of elements in the given array such that there exists an element strictly smaller and an element strictly greater than it. Examples: Input: arr [] = {11, 7, 2, 15}Output: 2Explanation: For arr[1] = 7, arr[0] is strictly greater than it and arr[2] is strictly smaller than it. Similarly for arr[1],
8 min read
Rearrange array such that even index elements are smaller and odd index elements are greater
Given an array, rearrange the array such that : If index i is even, arr[i] &lt;= arr[i+1]If index i is odd, arr[i] &gt;= arr[i+1] Note: There can be multiple answers. Examples: Input : arr[] = {2, 3, 4, 5} Output : arr[] = {2, 4, 3, 5} Explanation : Elements at even indexes are smaller and elements at odd indexes are greater than their next element
11 min read
Find next smaller element in Binary Search Tree
Given a binary search tree and a target value, the task is to find the next smaller element of the target value in the binary search tree. Examples : Input: 8 / \ 3 10 / \ \ 1 6 14 / \ / 4 7 13 Target: 7Output: 6Explanation: The next smaller element of 7 is 6 Input: 6 / \ 4 8 / \ / \ 2 5 7 10 Target: 5Output: 4Explanation: The next smaller element
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg