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 or equal element exists or not. If all elements in the right part of the array are greater than it, then print this element.
Steps for implementation-
- Traverse the input array/vector to pick elements one by one
- Run an inner loop for every element from its next element to the end
- Now if our element is greater than or equal to any element on its right then break the inner loop
- If the inner loop is broken then leave that element else print that element
Code-
// C++ program to find all elements in array // that are smaller than all elements // to their right. #include <bits/stdc++.h> using namespace std;
// Function to print all elements which are // smaller than all elements present // to their right void FindDesiredElements(vector< int >& arr)
{ // Size of input vector
int n = arr.size();
// Pick element one by one
for ( int i = 0; i < n; i++) {
int j = i + 1;
// Check all elements on its right
while (j < n) {
// If that element is greater than or equal to
// any element on its right then break the inner
// loop
if (arr[i] >= arr[j]) {
break ;
}
j++;
}
// If that inner loop is not broken then print that
// element
if (j == n) {
cout << arr[i] << " " ;
}
}
} // Driver Code int main()
{ vector< int > arr = { 6, 14, 13, 21, 17, 19 };
FindDesiredElements(arr);
return 0;
} |
import java.util.ArrayList;
import java.util.List;
class GFG {
// Function to print all elements which are
// smaller than all elements present
// to their right
static void findDesiredElements(List<Integer> arr) {
// Size of input list
int n = arr.size();
// Pick element one by one
for ( int i = 0 ; i < n; i++) {
int j = i + 1 ;
// Check all elements on its right
while (j < n) {
// If that element is greater than or equal to
// any element on its right then break the inner
// loop
if (arr.get(i) >= arr.get(j)) {
break ;
}
j++;
}
// If that inner loop is not broken then print that
// element
if (j == n) {
System.out.print(arr.get(i) + " " );
}
}
}
// Driver Code
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>();
arr.add( 6 );
arr.add( 14 );
arr.add( 13 );
arr.add( 21 );
arr.add( 17 );
arr.add( 19 );
findDesiredElements(arr);
}
} |
def find_desired_elements(arr):
# Size of input list
n = len (arr)
# Pick element one by one
for i in range (n):
j = i + 1
# Check all elements on its right
while j < n:
# If that element is greater than or equal to
# any element on its right then break the inner
# loop
if arr[i] > = arr[j]:
break
j + = 1
# If that inner loop is not broken then print that
# element
if j = = n:
print (arr[i], end = ' ' )
# Driver Code if __name__ = = '__main__' :
arr = [ 6 , 14 , 13 , 21 , 17 , 19 ]
find_desired_elements(arr)
|
using System;
using System.Collections.Generic;
class Program {
static void Main( string [] args) {
List< int > arr = new List< int > { 6, 14, 13, 21, 17, 19 };
FindDesiredElements(arr);
}
static void FindDesiredElements(List< int > arr) {
// Size of input list
int n = arr.Count;
// Pick element one by one
for ( int i = 0; i < n; i++) {
int j = i + 1;
// Check all elements on its right
while (j < n) {
// If that element is greater than or equal to
// any element on its right then break the inner
// loop
if (arr[i] >= arr[j]) {
break ;
}
j++;
}
// If that inner loop is not broken then print that
// element
if (j == n) {
Console.Write(arr[i] + " " );
}
}
}
} |
function findDesiredElements(arr) {
// Size of input array
var n = arr.length;
// Pick element one by one
for ( var i = 0; i < n; i++) {
var j = i + 1;
// Check all elements on its right
while (j < n) {
// If that element is greater than or equal to
// any element on its right, then break the inner loop
if (arr[i] >= arr[j]) {
break ;
}
j++;
}
// If the inner loop is not broken, then print that element
if (j == n) {
process.stdout.write(arr[i] + " " );
}
}
} // Driver Code var arr = [6, 14, 13, 21, 17, 19];
findDesiredElements(arr); |
Output-
6 13 17 19
Time complexity: O(N*N), because of two nested for loops
Auxiliary Space: O(1),because no extra space has been used
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++ 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 right void 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 Code int 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. |
# python 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 def 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 Code arr = []
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++ 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 right void 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 Code int 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 approach import 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 right def 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 Code arr = [ 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)