Given an array arr[] consisting of N integers, the task is to repeatedly remove elements that are smaller than the next element.
Examples:
Input: arr[] = {20, 10, 25, 30, 40}
Output: 40
Explanation:
Below are the operations that are performed:
- Current array: arr[] = {20, 10, 25, 30, 40}
Currently, arr[1](= 10) is less than arr[2](= 25). Therefore, removing arr[1] modifies the array to {20, 25, 30, 40}.- Currently arr[0](= 20) is less than arr[1](= 25). Therefore, removing arr[0] modifies the array to {25, 30, 40}.
- Currently, arr[0](= 25) is less than arr[1](= 30). Therefore, removing arr[0] modifies the array to {30, 40}.
- Currently, arr[0](= 30) is less than arr[1](= 40). Therefore, removing arr[0] modifies the array to {40}.
Therefore, the remaining array is arr[] = {40}.
Input: arr[] = {2, 5, 1, 0}
Output: 5 1 0
Naive Approach: The simplest approach to solve the problem is to traverse the array and remove the element if there are any greater elements in the range [i + 1, N – 1].
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach – Iterative: The above approach can be optimized by traversing the array from the end and keeping track of the largest element found and deleting the current element if it is lesser than the largest element. Follow the steps below to solve the problem:
- Initialize a vector, say res, to store the resultant array.
- Initialize a variable, say maxi as INT_MIN, to store the maximum value from the end.
- Traverse the array arr[] in a reverse manner and perform the following steps:
- If the value of arr[i] is less than the maxi then continue.
- Otherwise, push the element arr[i] in res and update the value of maxi to the maximum of maxi and arr[i].
- Reverse the vector res.
- After completing the above steps, print the vector res as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to minimize length of an // array by repeatedly removing elements // that are smaller than the next element void DeleteSmaller( int arr[], int N) { // Stores the maximum value in // the range [i, N] int maxi = INT_MIN; // Stores the resultant array vector< int > res; // Iterate until i is atleast 0 for ( int i = N - 1; i >= 0; i--) { // If arr[i] is less than maxi if (arr[i] < maxi) continue ; // Push the arr[i] in res res.push_back(arr[i]); // Update the value of maxi maxi = max(maxi, arr[i]); } // Reverse the vector res reverse(res.begin(), res.end()); // Print the vector res for ( auto x : res) cout << x << " " ; } // Driver Code int main() { int arr[] = { 2, 5, 1, 0 }; int N = sizeof (arr) / sizeof (arr[0]); DeleteSmaller(arr, N); return 0; } |
Java
// Java program for the above approach import java.util.*; class GFG { // Function to minimize length of an // array by repeatedly removing elements // that are smaller than the next element static void DeleteSmaller( int arr[], int N) { // Stores the maximum value in // the range [i, N] int maxi = Integer.MIN_VALUE; // Stores the resultant array List<Integer> res = new ArrayList<Integer>(); // Iterate until i is atleast 0 for ( int i = N - 1 ; i >= 0 ; i--) { // If arr[i] is less than maxi if (arr[i] < maxi) continue ; // Push the arr[i] in res res.add(arr[i]); // Update the value of maxi maxi = Math.max(maxi, arr[i]); } // Reverse the vector res Collections.reverse(res); // Print the vector res for ( int i = 0 ; i < res.size(); i++) System.out.println(res.get(i) + " " ); } // Driver Code public static void main(String[] args) { int arr[] = { 2 , 5 , 1 , 0 }; int N = arr.length; DeleteSmaller(arr, N); } } // This code is contributed by Samim Hossain Mondal |
Python3
# Python3 program for the above approach # Function to minimize length of an # array by repeatedly removing elements # that are smaller than the next element def DeleteSmaller(arr, N): # Stores the maximum value in # the range [i, N] maxi = - 10 * * 9 # Stores the resultant array res = [] # Iterate until i is atleast 0 for i in range (N - 1 , - 1 , - 1 ): # If arr[i] is less than maxi if (arr[i] < maxi): continue # Push the arr[i] in res res.append(arr[i]) # Update the value of maxi maxi = max (maxi, arr[i]) # Reverse the vector res res = res[:: - 1 ] # Print vector res print ( * res) # Driver Code if __name__ = = '__main__' : arr = [ 2 , 5 , 1 , 0 ] N = len (arr) DeleteSmaller(arr, N) # This code is contributed by mohit kumar 29. |
C#
// C# program for the above approach using System; using System.Collections.Generic; class GFG { // Function to minimize length of an // array by repeatedly removing elements // that are smaller than the next element static void DeleteSmaller( int [] arr, int N) { // Stores the maximum value in // the range [i, N] int maxi = Int32.MinValue; // Stores the resultant array List< int > res = new List< int >(); // Iterate until i is atleast 0 for ( int i = N - 1; i >= 0; i--) { // If arr[i] is less than maxi if (arr[i] < maxi) continue ; // Push the arr[i] in res res.Add(arr[i]); // Update the value of maxi maxi = Math.Max(maxi, arr[i]); } // Reverse the vector res res.Reverse(); // Print the vector res foreach ( int x in res) Console.Write(x + " " ); } // Driver Code public static void Main() { int [] arr = { 2, 5, 1, 0 }; int N = arr.Length; DeleteSmaller(arr, N); } } // This code is contributed by SURENDRA_GANGWAR |
Javascript
<script> // Javascript program for the above approach // Function to minimize length of an // array by repeatedly removing elements // that are smaller than the next element function DeleteSmaller(arr, N) { // Stores the maximum value in // the range [i, N] let maxi = Number.MIN_SAFE_INTEGER; // Stores the resultant array let res = []; // Iterate until i is atleast 0 for (let i = N - 1; i >= 0; i--) { // If arr[i] is less than maxi if (arr[i] < maxi) continue ; // Push the arr[i] in res res.push(arr[i]); // Update the value of maxi maxi = Math.max(maxi, arr[i]); } // Reverse the vector res res.reverse(); // Print the vector res for (let x of res) document.write(x + " " ); } // Driver Code let arr = [2, 5, 1, 0]; let N = arr.length; DeleteSmaller(arr, N); // This code is contributed by gfgking. </script> |
5 1 0
Time Complexity: O(N)
Auxiliary Space: O(N)
Efficient Approach – Recursive: The above approach can also be implemented using recursion. Follow the steps below to solve the problem:
- Initialize a vector, say res to store the resultant array.
- Define a recursive function, say RecursiveDeleteFunction(int i) to delete element smaller than next element:
- If the value of i is equal to N then return INT_MIN.
- Call recursively call the function RecursiveDeleteFunction(i+1) and store the returned value in a variable say curr.
- If the value of arr[i] is at least curr then push arr[i] in vector res and update the value of curr as the maximum of curr and arr[i].
- Now, return the curr.
- Call the function RecursiveDeleteFunction(0) to remove the smaller elements to next elements and then, reverse the vector res.
- After completing the above steps, print the vector res as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Recursive function to remove // all elements which are smaller // than the next element int RecursiveDeleteFunction( int arr[], int N, int i, vector< int >& res) { // If i is equal to N if (i == N) return INT_MIN; // Recursive call to the next // element int curr = RecursiveDeleteFunction( arr, N, i + 1, res); // If arr[i] is greater than the // or equal to curr if (arr[i] >= curr) { // Push the arr[i] in res res.push_back(arr[i]); // Update the value curr curr = max(arr[i], curr); } // Return the value of curr return curr; } // Function to minimize length of an // array by repeatedly removing elements // that are smaller than the next element void DeleteSmaller( int arr[], int N) { // Stores maximum value in the // the range [i, N] int maxi = INT_MIN; // Stores the resultant array vector< int > res; // Recursive call to function // RecursiveDeleteFunction RecursiveDeleteFunction(arr, N, 0, res); // Reverse the vector res reverse(res.begin(), res.end()); // Print the vector res for ( auto x : res) cout << x << " " ; } // Driver Code int main() { int arr[] = { 2, 5, 1, 0 }; int N = sizeof (arr) / sizeof (arr[0]); DeleteSmaller(arr, N); return 0; } |
Java
// Java program for the above approach import java.util.*; public class GFG { // Recursive function to remove // all elements which are smaller // than the next element static int RecursiveDeleteFunction( int []arr, int N, int i, ArrayList<Integer> res) { // If i is equal to N if (i == N) return Integer.MIN_VALUE; // Recursive call to the next // element int curr = RecursiveDeleteFunction( arr, N, i + 1 , res); // If arr[i] is greater than the // or equal to curr if (arr[i] >= curr) { // Push the arr[i] in res res.add(arr[i]); // Update the value curr curr = Math.max(arr[i], curr); } // Return the value of curr return curr; } // Function to minimize length of an // array by repeatedly removing elements // that are smaller than the next element static void DeleteSmaller( int []arr, int N) { // Stores maximum value in the // the range [i, N] int maxi = Integer.MIN_VALUE; // Stores the resultant array ArrayList<Integer> res = new ArrayList<Integer>(); // Recursive call to function // RecursiveDeleteFunction RecursiveDeleteFunction(arr, N, 0 , res); // Reverse the vector res Collections.reverse(res); // Print the vector res for ( int i = 0 ; i < res.size(); i++) System.out.print(res.get(i) + " " ); } // Driver Code public static void main(String args[]) { int []arr = { 2 , 5 , 1 , 0 }; int N = arr.length; DeleteSmaller(arr, N); } } // This code is contributed by Samim Hossain Mondal. |
Python3
# Python3 program for the above approach # Recursive function to remove # all elements which are smaller # than the next element def RecursiveDeleteFunction(arr, N, i, res) : # If i is equal to N if (i = = N) : return - 10 * * 9 # Recursive call to the next # element curr = RecursiveDeleteFunction( arr, N, i + 1 , res) # If arr[i] is greater than the # or equal to curr if (arr[i] > = curr) : # Push the arr[i] in res res.append(arr[i]) # Update the value curr curr = max (arr[i], curr) # Return the value of curr return curr # Function to minimize length of an # array by repeatedly removing elements # that are smaller than the next element def DeleteSmaller(arr, N) : # Stores maximum value in the # the range [i, N] maxi = - 10 * * 9 # Stores the resultant array res = [] # Recursive call to function # RecursiveDeleteFunction RecursiveDeleteFunction(arr, N, 0 , res) # Reverse the vector res res = res[:: - 1 ] # Print the vector res for x in res : print (x, end = " " ) # Driver Code if __name__ = = '__main__' : arr = [ 2 , 5 , 1 , 0 ] N = len (arr) DeleteSmaller(arr, N) # This code is contributed by sanjoy_62. |
C#
// C# program for the above approach using System; using System.Collections.Generic; class GFG { // Recursive function to remove // all elements which are smaller // than the next element static int RecursiveDeleteFunction( int []arr, int N, int i, List< int > res) { // If i is equal to N if (i == N) return Int32.MinValue; // Recursive call to the next // element int curr = RecursiveDeleteFunction( arr, N, i + 1, res); // If arr[i] is greater than the // or equal to curr if (arr[i] >= curr) { // Push the arr[i] in res res.Add(arr[i]); // Update the value curr curr = Math.Max(arr[i], curr); } // Return the value of curr return curr; } // Function to minimize length of an // array by repeatedly removing elements // that are smaller than the next element static void DeleteSmaller( int []arr, int N) { // Stores maximum value in the // the range [i, N] int maxi = Int32.MinValue; // Stores the resultant array List< int > res = new List< int >(); // Recursive call to function // RecursiveDeleteFunction RecursiveDeleteFunction(arr, N, 0, res); // Reverse the vector res res.Reverse(); // Print the vector res for ( int i = 0; i < res.Count; i++) Console.Write(res[i] + " " ); } // Driver Code public static void Main() { int []arr = { 2, 5, 1, 0 }; int N = arr.Length; DeleteSmaller(arr, N); } } // This code is contributed by Samim Hossain Mondal. |
Javascript
<script> // JavaScript Program to implement // the above approach // Recursive function to remove // all elements which are smaller // than the next element function RecursiveDeleteFunction( arr, N, i, res) { // If i is equal to N if (i == N) return -999999999; // Recursive call to the next // element let curr = RecursiveDeleteFunction( arr, N, i + 1, res); // If arr[i] is greater than the // or equal to curr if (arr[i] >= curr) { // Push the arr[i] in res res.push(arr[i]); // Update the value curr curr = Math.max(arr[i], curr); } // Return the value of curr return curr; } // Function to minimize length of an // array by repeatedly removing elements // that are smaller than the next element function DeleteSmaller(arr, N) { // Stores maximum value in the // the range [i, N] let maxi = Number.MIN_VALUE; // Stores the resultant array let res = []; // Recursive call to function // RecursiveDeleteFunction RecursiveDeleteFunction(arr, N, 0, res); // Reverse the vector res res.reverse(); // Print the vector res document.write(res); } // Driver Code let arr = [2, 5, 1, 0]; let N = arr.length; DeleteSmaller(arr, N); // This code is contributed by Potta Lokesh </script> |
5 1 0
Time Complexity: O(N)
Auxiliary Space: O(N)
Optimized Solution(using stack data structure)
Approach- We can use a stack data structure.First iterate through the array from left to right, and for each element, we will compare it with the top element of the stack. If the current element is greater than the top element, we will pop the top element from the stack until either the stack becomes empty or the top element is greater than the current element. Finally, we will push the current element onto the stack.
Implementation of the above approach
C++
#include <iostream> #include <stack> #include <vector> #include <algorithm> // add this line using namespace std; vector< int > removeElements(vector< int >& arr) { stack< int > s; for ( int i = 0; i < arr.size(); i++) { while (!s.empty() && s.top() < arr[i]) { s.pop(); } s.push(arr[i]); } vector< int > result; while (!s.empty()) { result.push_back(s.top()); s.pop(); } reverse(result.begin(), result.end()); return result; } int main() { vector< int > arr = {2,5,1,0}; vector< int > result = removeElements(arr); for ( int i = 0; i < result.size(); i++) { cout << result[i] << " " ; } cout << endl; return 0; } |
Java
import java.util.*; public class Main { public static List<Integer> removeElements(List<Integer> arr) { Stack<Integer> s = new Stack<>(); for ( int i = 0 ; i < arr.size(); i++) { // keep removing elements from the stack that are smaller than the current element while (!s.empty() && s.peek() < arr.get(i)) { s.pop(); } // push the current element onto the stack s.push(arr.get(i)); } List<Integer> result = new ArrayList<>(); // pop elements from the stack and add them to the result list in reverse order while (!s.empty()) { result.add(s.peek()); s.pop(); } Collections.reverse(result); return result; } public static void main(String[] args) { List<Integer> arr = Arrays.asList( 2 , 5 , 1 , 0 ); List<Integer> result = removeElements(arr); for ( int i = 0 ; i < result.size(); i++) { System.out.print(result.get(i) + " " ); } System.out.println(); } } |
Python
def removeElements(arr): s = [] for i in range ( len (arr)): while s and s[ - 1 ] < arr[i]: s.pop() s.append(arr[i]) result = [] while s: result.append(s.pop()) result.reverse() return result arr = [ 2 , 5 , 1 , 0 ] result = removeElements(arr) print (result) |
C#
using System; using System.Collections.Generic; using System.Linq; public class GFG { public static List< int > RemoveElements(List< int > arr) { Stack< int > s = new Stack< int >(); for ( int i = 0; i < arr.Count; i++) { while (s.Count > 0 && s.Peek() < arr[i]) { s.Pop(); } s.Push(arr[i]); } List< int > result = new List< int >(); while (s.Count > 0) { result.Add(s.Peek()); s.Pop(); } result.Reverse(); return result; } public static void Main() { List< int > arr = new List< int > {2, 5, 1, 0}; List< int > result = RemoveElements(arr); for ( int i = 0; i < result.Count; i++) { Console.Write(result[i] + " " ); } Console.WriteLine(); } } |
Javascript
function removeElements(arr) { let s = []; for (let i = 0; i < arr.length; i++) { while (s.length > 0 && s[s.length - 1] < arr[i]) { s.pop(); } s.push(arr[i]); } let result = []; while (s.length > 0) { result.push(s[s.length - 1]); s.pop(); } result.reverse(); return result; } let arr = [2, 5, 1, 0]; let result = removeElements(arr); for (let i = 0; i < result.length; i++) { console.log(result[i] + " " ); } console.log(); |
5 1 0
Time complexity: O(n), where n is the length of the input array ‘arr’
The auxiliary space:O(n), because in the worst case scenario the entire input array may need to be stored in the stack before any elements are removed.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!