Minimum elements to be removed from the ends to make the array sorted

Given an array arr[] of length N, the task is to remove the minimum number of elements from the ends of the array to make the array non-decreasing. Elements can only be removed from the left or the right end.
Examples:Â
Input: arr[] = {1, 2, 4, 1, 5}Â
Output: 2Â
We can’t make the array sorted after one removal.Â
But if we remove 2 elements from the right end, theÂ
array becomes {1, 2, 4} which is sorted.
Input: arr[] = {3, 2, 1}Â
Output: 2Â
Approach: A very simple solution to this problem is to find the length of the longest non-decreasing subarray of the given array. Let’s say the length is L. So, the count of elements that need to be removed will be N – L. The length of the longest non-decreasing subarray can be easily found using the approach discussed in this article.
Below is the implementation of the above approach:Â
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Function to return the minimum number// of elements to be removed from the ends// of the array to make it sortedint findMin(int* arr, int n){Â
    // To store the final answer    int ans = 1;Â
    // Two pointer loop    for (int i = 0; i < n; i++) {        int j = i + 1;Â
        // While the array is increasing increment j        while (j < n and arr[j] >= arr[j - 1])            j++;Â
        // Updating the ans        ans = max(ans, j - i);Â
        // Updating the left pointer        i = j - 1;    }Â
    // Returning the final answer    return n - ans;}Â
// Driver codeint main(){Â Â Â Â int arr[] = { 3, 2, 1 };Â Â Â Â int n = sizeof(arr) / sizeof(int);Â
    cout << findMin(arr, n);Â
    return 0;} |
Java
// Java implementation of the approach class GFG {         // Function to return the minimum number     // of elements to be removed from the ends     // of the array to make it sorted     static int findMin(int arr[], int n)     {              // To store the final answer         int ans = 1;              // Two pointer loop         for (int i = 0; i < n; i++)         {             int j = i + 1;                  // While the array is increasing increment j             while (j < n && arr[j] >= arr[j - 1])                 j++;                  // Updating the ans             ans = Math.max(ans, j - i);                  // Updating the left pointer             i = j - 1;         }              // Returning the final answer         return n - ans;     }          // Driver code     public static void main (String[] args)    {         int arr[] = { 3, 2, 1 };         int n = arr.length;         System.out.println(findMin(arr, n));     } }Â
// This code is contributed by AnkitRai01 |
Python3
# Python3 implementation of the approachÂ
# Function to return the minimum number# of elements to be removed from the ends# of the array to make it sorteddef findMin(arr, n):Â
    # To store the final answer    ans = 1Â
    # Two pointer loop    for i in range(n):        j = i + 1Â
        # While the array is increasing increment j        while (j < n and arr[j] >= arr[j - 1]):            j += 1Â
        # Updating the ans        ans = max(ans, j - i)Â
        # Updating the left pointer        i = j - 1Â
    # Returning the final answer    return n - ansÂ
# Driver codearr = [3, 2, 1]n = len(arr)Â
print(findMin(arr, n))Â
# This code is contributed by Mohit Kumar |
C#
// C# implementation of the approach using System;Â
class GFG {Â Â Â Â Â // Function to return the minimum number // of elements to be removed from the ends // of the array to make it sorted static int findMin(int []arr, int n) { Â
    // To store the readonly answer     int ans = 1; Â
    // Two pointer loop     for (int i = 0; i < n; i++)     {         int j = i + 1; Â
        // While the array is increasing increment j         while (j < n && arr[j] >= arr[j - 1])             j++; Â
        // Updating the ans         ans = Math.Max(ans, j - i); Â
        // Updating the left pointer         i = j - 1;     } Â
    // Returning the readonly answer     return n - ans; } Â
// Driver code public static void Main(String[] args){ Â Â Â Â int []arr = { 3, 2, 1 }; Â Â Â Â int n = arr.Length; Â Â Â Â Console.WriteLine(findMin(arr, n)); } }Â
// This code is contributed by Rajput-Ji |
Javascript
<script>// Java script implementation of the approach         // Function to return the minimum number    // of elements to be removed from the ends    // of the array to make it sorted    function findMin(arr,n)    {             // To store the final answer        let ans = 1;             // Two pointer loop        for (let i = 0; i < n; i++)        {            let j = i + 1;                 // While the array is increasing increment j            while (j < n && arr[j] >= arr[j - 1])                j++;                 // Updating the ans            ans = Math.max(ans, j - i);                 // Updating the left pointer            i = j - 1;        }             // Returning the final answer        return n - ans;    }         // Driver code        let arr = [ 3, 2, 1 ];        let n = arr.length;        document.write(findMin(arr, n));     // This code is contributed by sravan kumar G</script> |
2
Â
Time Complexity: O(N )
Auxiliary Space: O(1)
Method #2: Using Dynamic Programming
The idea is to use dynamic programming to keep track of the length of the increasing subsequence ending at each index.Â
Step-by-Step Algorithm:
- Initialize ans to 1 and create a new array dp of length n, where dp[i] will store the length of the longest increasing subsequence ending at index i.
- Set dp[0] to 1 since the longest increasing subsequence ending at index 0 has length 1.
- Loop through the array from index 1 to n-1:
a) Set dp[i] to 1.
b) If arr[i] is greater than or equal to arr[i-1], add the length of the increasing subsequence ending at i-1 to dp[i]. This means that we’re extending the increasing subsequence ending at i-1 to include the current element arr[i].
c) Update ans to be the maximum value between ans and dp[i]. - Delete the dp array to free up memory.
- Return n – ans as the minimum number of elements that need to be removed to make the array sorted.
C++
#include <bits/stdc++.h>using namespace std;Â
int findMin(int* arr, int n){Â Â Â Â int ans = 1;Â Â Â Â int* dp = new int[n];Â Â Â Â dp[0] = 1;Â
    for (int i = 1; i < n; i++) {        dp[i] = 1;        if (arr[i] >= arr[i - 1])            dp[i] += dp[i - 1];        ans = max(ans, dp[i]);    }Â
    delete[] dp;    return n - ans;}Â
int main(){Â Â Â Â int arr[] = { 3, 2, 1 };Â Â Â Â int n = sizeof(arr) / sizeof(int);Â
    cout << findMin(arr, n);Â
    return 0;} |
Java
import java.util.*;Â
public class GFG {    // Function to find the minimum number of elements to    // remove from an array    public static int findMin(int[] arr, int n)    {        int ans = 1;        int[] dp = new int[n];        dp[0] = 1;Â
        // Calculate the length of the longest        // non-decreasing subsequence ending at each index        // Dynamic Programming approach to find the length        // of        // Longest Increasing Subsequence        for (int i = 1; i < n; i++) {            dp[i] = 1;            if (arr[i] >= arr[i - 1])                dp[i] += dp[i - 1];            ans = Math.max(ans, dp[i]);        }        // Return the minimum number of elements to remove        return n - ans;    }Â
    public static void main(String[] args)    {        int[] arr = { 3, 2, 1 };        int n = arr.length;        // Call the FindMin function and print the result        System.out.println(findMin(arr, n));    }} |
C#
using System;Â
class Program {    // Function to find the minimum number of elements to    // remove from an array    static int FindMin(int[] arr, int n)    {        int ans = 1;        int[] dp = new int[n];        dp[0] = 1;Â
        // Calculate the length of the longest        // non-decreasing subsequence ending at each index        for (int i = 1; i < n; i++) {            dp[i] = 1;            if (arr[i] >= arr[i - 1])                dp[i] += dp[i - 1];            ans = Math.Max(ans, dp[i]);        }Â
        // Free the dynamically allocated memory for the dp        // array        Array.Clear(dp, 0, dp.Length);Â
        // Return the minimum number of elements to remove        return n - ans;    }Â
    static void Main(string[] args)    {        int[] arr = { 3, 2, 1 };        int n = arr.Length;Â
        // Call the FindMin function and print the result        Console.WriteLine(FindMin(arr, n));    }} |
Python3
def findMin(arr, n):Â Â Â Â ans = 1Â Â Â Â dp = [1] * nÂ
    for i in range(1, n):        if arr[i] >= arr[i-1]:            dp[i] += dp[i-1]        ans = max(ans, dp[i])Â
    return n - ansÂ
arr = [3, 2, 1]n = len(arr)Â
print(findMin(arr, n)) |
Javascript
function findMin(arr, n) {Â Â Â Â let ans = 1;Â Â Â Â let dp = new Array(n);Â Â Â Â dp[0] = 1;Â
    for (let i = 1; i < n; i++) {        dp[i] = 1;        if (arr[i] >= arr[i - 1]) dp[i] += dp[i - 1];        ans = Math.max(ans, dp[i]);    }Â
    return n - ans;}Â
let arr = [3, 2, 1];let n = arr.length;Â
console.log(findMin(arr, n));Â
// This code is contributed by sarojmcy2e |
2
Complexity Analysis :
Time Complexity: O(n) where n is the lengthÂ
This is because the algorithm loops through the array once, so the time complexity is O(n).
Auxiliary Space: O(1)Â
This is because we uses an additional array of size n, so the space complexity is O(n). However, since we delete the dp array before returning, the actual space used by the algorithm is O(1) in terms of memory that is not reused.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



