Find all Array elements that are smaller than all elements to their right - GeeksforGeeks

05 Apr, 2022
Given an array arr[] containing N positive integers. The task is to find all the elements which are smaller than all the elements to their right.
Examples:
Input: arr[] = {6, 14, 13, 21, 17, 19}Output: [6, 13, 17, 19]Explanation: All the elements in the output are following the condition.
Input: arr[] = {10, 3, 4, 8, 7}Output: [3, 4, 7]
Naive approach: This approach uses two loops. For each element, traverse the array to its right and check if any smaller element exists or not. If all elements in the right part of the array are greater than it, then print this element. 
Time complexity: O(N*N)Auxiliary Space: O(1)
Efficient approach: In the efficient approach, the idea is to use a Stack. Follow the steps mentioned below:
Iterate the array from the beginning of the array.
For every element in the array, pop all the elements present in the stack that are greater than it and then push it into the stack.
If no element is greater than it, then the current element is an answer.
At last, the stack remains with elements that are smaller than all elements present to their right.
Below is the code implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program to find all elements in array// that are smaller than all elements// to their right.#include <iostream>#include <stack>#include <vector>using namespace std; // Function to print all elements which are// smaller than all elements present// to their rightvoid FindDesiredElements(vector<int> const& arr){    // Create an empty stack    stack<int> stk;     // Do for each element    for (int i : arr) {        // Pop all the elements that        // are greater than the        // current element        while (!stk.empty() && stk.top() > i) {            stk.pop();        }         // Push current element into the stack        stk.push(i);    }     // Print all elements in the stack    while (!stk.empty()) {        cout << stk.top() << " ";        stk.pop();    }} // Driver Codeint main(){    vector<int> arr = { 6, 14, 13, 21, 17, 19 };     FindDesiredElements(arr);    return 0;}
// Java program to find all elements in array// that are smaller than all elements// to their right.import java.util.ArrayList;import java.util.Stack; class GFG {   // Function to print all elements which are  // smaller than all elements present  // to their right  static void FindDesiredElements(ArrayList<Integer> arr)  {     // Create an empty stack    Stack<Integer> stk = new Stack<Integer>();     // Do for each element    for (int i : arr)    {             // Pop all the elements that      // are greater than the      // current element      while (!stk.empty() && stk.peek() > i) {        stk.pop();      }       // Push current element into the stack      stk.push(i);    }     // Print all elements in the stack    while (!stk.empty()) {      System.out.print(stk.peek() + " ");      stk.pop();    }  }   // Driver Code  public static void main(String args[])  {    ArrayList<Integer> arr = new ArrayList<Integer>();    arr.add(6);    arr.add(14);    arr.add(13);    arr.add(21);    arr.add(17);    arr.add(19);     FindDesiredElements(arr);  }} // This code is contributed by saurabh_jaiswal.
# Oython program to find all elements in array# that are smaller than all elements# to their right. # Function to print all elements which are# smaller than all elements present# to their rightdef FindDesiredElements(arr):     # Create an empty stack    stk = []     # Do for each element    for i in arr :         # Pop all the elements that        # are greater than the        # current element        while (len(stk)!=0 and stk[len(stk)-1] > i):            stk.pop()         # Push current element into the stack        stk.append(i)     # Print all elements in the stack    while (len(stk) != 0):        print(stk[len(stk)-1],end = " ")        stk.pop() # Driver Codearr = []arr.append(6)arr.append(14)arr.append(13)arr.append(21)arr.append(17)arr.append(19) FindDesiredElements(arr) # This code is contributed by shinjanpatra
// C# program to find all elements in array// that are smaller than all elements// to their right.using System;using System.Collections.Generic;public class GFG {   // Function to print all elements which are  // smaller than all elements present  // to their right  static void FindDesiredElements(List<int> arr) {     // Create an empty stack    Stack<int> stk = new Stack<int>();     // Do for each element    foreach (int i in arr) {       // Pop all the elements that      // are greater than the      // current element      while (stk.Count!=0 && stk.Peek() > i) {        stk.Pop();      }       // Push current element into the stack      stk.Push(i);    }     // Print all elements in the stack    while (stk.Count>0) {      Console.Write(stk.Peek() + " ");      stk.Pop();    }  }   // Driver Code  public static void Main(String []args) {    List<int> arr = new List<int>();    arr.Add(6);    arr.Add(14);    arr.Add(13);    arr.Add(21);    arr.Add(17);    arr.Add(19);     FindDesiredElements(arr);  }} // This code is contributed by Rajput-Ji
<script>// javascript program to find all elements in array// that are smaller than all elements// to their right.     // Function to print all elements which are    // smaller than all elements present    // to their right    function FindDesiredElements( arr) {         // Create an empty stack        var stk = [];         // Do for each element        for (var i of arr) {             // Pop all the elements that            // are greater than the            // current element            while (stk.length!=0 && stk[stk.length-1] > i) {                stk.pop();            }             // Push current element into the stack            stk.push(i);        }         // Print all elements in the stack        while (stk.length != 0) {            document.write(stk[stk.length-1] + " ");            stk.pop();        }    }     // Driver Code        var arr = [];        arr.push(6);        arr.push(14);        arr.push(13);        arr.push(21);        arr.push(17);        arr.push(19);         FindDesiredElements(arr); // This code is contributed by Rajput-Ji</script>
  
19 17 13 6 
 Time complexity: O(N)Auxiliary Space: O(N)
Space Optimized approach: The idea is to traverse the array from right to left (reverse order) and maintain an auxiliary variable that stores the minimum element found so far. This approach will neglect the use of stack. Follow the below steps:
Start iterating from the end of the array.
If the current element is smaller than the minimum so far, then the element is found. Update the value storing minimum value so far. Print all such values as the answer.
 Below is the implementation of the above approach.
 
C++
Java
Python3
C#
Javascript
// C++ program to print all elements which are// smaller than all elements present to their right #include <iostream>#include <limits.h>using namespace std; // Function to print all elements which are// smaller than all elements// present to their rightvoid FindDesiredElements(int arr[], int n){    int min_so_far = INT_MAX;     // Traverse the array from right to left    for (int j = n - 1; j >= 0; j--) {        // If the current element is greater        //  than the maximum so far, print it        // and update `max_so_far`        if (arr[j] <= min_so_far) {            min_so_far = arr[j];            cout << arr[j] << " ";        }    }} // Driver Codeint main(){    int arr[] = { 6, 14, 13, 21, 17, 19 };    int N = sizeof(arr) / sizeof(arr[0]);     FindDesiredElements(arr, N);    return 0;}
// Java program for the above approachimport java.util.*;class GFG {   // Function to print all elements which are  // smaller than all elements  // present to their right  static void FindDesiredElements(int[] arr, int n)  {    int min_so_far = Integer.MAX_VALUE;     // Traverse the array from right to left    for (int j = n - 1; j >= 0; j--)    {       // If the current element is greater      //  than the maximum so far, print it      // and update `max_so_far`      if (arr[j] <= min_so_far) {        min_so_far = arr[j];        System.out.print(arr[j] + " ");      }    }  }   // Driver Code  public static void main(String[] args)  {    int[] arr = { 6, 14, 13, 21, 17, 19 };    int N = arr.length;     FindDesiredElements(arr, N);   }} // This code is contributed by code_hunt.
# Python code for the above approach # Function to print all elements which are# smaller than all elements# present to their rightdef FindDesiredElements(arr, n):    min_so_far = 10 ** 9;     # Traverse the array from right to left    for j in range(n - 1, -1, -1):             # If the current element is greater        #  than the maximum so far, print it        # and update `max_so_far`        if (arr[j] <= min_so_far):            min_so_far = arr[j];            print(arr[j], end=" ") # Driver Codearr = [6, 14, 13, 21, 17, 19];N = len(arr) FindDesiredElements(arr, N); # This code is contributed by Saurabh Jaiswal
// C# program to print all elements which are// smaller than all elements present to their right using System;class GFG {    // Function to print all elements which are    // smaller than all elements    // present to their right    static void FindDesiredElements(int[] arr, int n)    {        int min_so_far = Int32.MaxValue;         // Traverse the array from right to left        for (int j = n - 1; j >= 0; j--) {            // If the current element is greater            //  than the maximum so far, print it            // and update `max_so_far`            if (arr[j] <= min_so_far) {                min_so_far = arr[j];                Console.Write(arr[j] + " ");            }        }    }     // Driver Code    public static void Main()    {        int[] arr = { 6, 14, 13, 21, 17, 19 };        int N = arr.Length;         FindDesiredElements(arr, N);    }}
<script>      // JavaScript code for the above approach       // Function to print all elements which are      // smaller than all elements      // present to their right      function FindDesiredElements(arr, n)      {          let min_so_far = Number.MAX_VALUE;           // Traverse the array from right to left          for (let j = n - 1; j >= 0; j--)          {                         // If the current element is greater              //  than the maximum so far, print it              // and update `max_so_far`              if (arr[j] <= min_so_far) {                  min_so_far = arr[j];                  document.write(arr[j] + " ");              }          }      }       // Driver Code      let arr = [6, 14, 13, 21, 17, 19];      let N = arr.length;       FindDesiredElements(arr, N); // This code is contributed by Potta Lokesh  </script>
  
19 17 13 6 
 
Time complexity: O(N)Auxiliary Space: O(1)
 
lokeshpotta20
_saurabh_jaiswal
ukasp
code_hunt
Rajput-Ji
simranarora5sos
shinjanpatra
Algo-Geek 2021
Algo Geek
Arrays
Greedy
Mathematical
Arrays
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if the given string is valid English word or not
Sort strings on the basis of their numeric part
Divide given number into two even parts
Smallest set of vertices to visit all nodes of the given Graph
Bit Manipulation technique to replace boolean arrays of fixed size less than 64
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation