Open In App

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

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

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:
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:

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 sorted
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 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 code
int 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 sorted
def 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 code
arr = [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>


Output: 

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:

  1. 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.
  2. Set dp[0] to 1 since the longest increasing subsequence ending at index 0 has length 1.
  3. 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].
  4. Delete the dp array to free up memory.
  5. 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


Output

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads