Smallest prefix to be deleted such that remaining array can be rearranged to form a sorted array

Given an array arr[] consisting of N integers, the task is to find the minimum length of the prefix needed to be deleted such that the remaining array elements can be rearranged repeatedly selecting the first or the last element one by one to form a sorted array.

Examples:

Input: arr[] = {6, 5, 4, 3, 4}
Output: 3
Explanation:
To make an array sorted according to the given condition, remove the first 3 elements.
After deletion, the array arr[] is modified to {3, 4}.
From the array arr[], selecting the first elements one by one, i.e. arr[0] -> arr[1], forms a sorted array {3, 4}.

Input: arr[] = {1, 3, 4, 2}
Output: 0
Explanation:
There is no need to delete any prefix.
By selecting array elements in the order arr[0] -> arr[3] -> arr[1] -> arr[2], forms a sorted array {1, 2, 3, 4}.

Naive Approach: The simplest approach is to delete all possible lengths of the prefix from the given array and for every prefix, check if a sorted array can be formed from the remaining array elements by removal of those prefixes. If found to be true, then print the minimum length of the prefix deleted. 



Time Complexity: O(N2)
Auxiliary Space: O(N)

Efficient Approach: The above approach can be optimized by observing that the resultant suffix must be of the form arr[1] ≤ arr[2] ≤ … ≥ arr[N – 2] ≥ arr[N – 1] where N is the length of the remaining array and suffix is of the maximum length. Follow the steps below:

  • Initialize a variable index to N – 1.
  • Traverse the array from the end and stop at the point where arr[index – 1] ≤ arr[index].
  • As the iteration proceeds, keep decrementing answer.
  • After completing all the above steps, print the value of the index which is the minimum length of the prefix that must be deleted.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum length
// of prefix required to be deleted
int findMinLength(vector<int>& arr)
{
    // Stores index to be returned
    int index = (int)arr.size() - 1;
 
    // Iterate until previous element
    // is <= current index
    while (index > 0
           && arr[index] >= arr[index - 1]) {
 
        // Decrementing index
        index--;
    }
 
    // Return index
    return index;
}
 
// Driver Code
int main()
{
 
    // Given arr[]
    vector<int> arr = { 7, 8, 5, 0, -1,
                        -1, 0, 1, 2, 3, 4 };
 
    // Function Call
    cout << findMinLength(arr);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for above approach
import java.util.*;
import java.io.*;
 
class GFG{
      
// Function to find the minimum length
// of prefix required to be deleted
static int findMinLength(int[] arr)
{
     
    // Stores index to be returned
    int index = (int)arr.length - 1;
   
    // Iterate until previous element
    // is <= current index
    while (index > 0 && arr[index] >=
                        arr[index - 1])
    {
         
        // Decrementing index
        index--;
    }
   
    // Return index
    return index;
}
 
// Driver code
public static void main(String args[])
{
     
    // Given arr[]
    int arr[]=  { 7, 8, 5, 0, -1,
                 -1, 0, 1, 2, 3, 4 };
    int n = arr.length;
     
    // Function call
    System.out.println(findMinLength(arr));
}
}
 
// This code is contributed by bikram2001jha

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for above approach
 
# Function to find the minimum length
# of prefix required to be deleted
def findMinLength(arr):
   
    # Stores index to be returned
    index = len(arr) - 1;
 
    # Iterate until previous element
    # is <= current index
    while (index > 0 and arr[index] >= arr[index - 1]):
       
        # Decrementing index
        index -= 1;
 
    # Return index
    return index;
 
# Driver code
if __name__ == '__main__':
   
    # Given arr
    arr = [7, 8, 5, 0, -1,
           -1, 0, 1, 2, 3, 4];
    n = len(arr);
 
    # Function call
    print(findMinLength(arr));
 
# This code is contributed by Princi Singh

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for above approach
using System;
 
class GFG{
      
// Function to find the minimum length
// of prefix required to be deleted
static int findMinLength(int[] arr)
{
     
    // Stores index to be returned
    int index = (int)arr.Length - 1;
   
    // Iterate until previous element
    // is <= current index
    while (index > 0 && arr[index] >=
                        arr[index - 1])
    {
         
        // Decrementing index
        index--;
    }
     
    // Return index
    return index;
}
 
// Driver code
public static void Main(String []args)
{
     
    // Given []arr
    int []arr =  { 7, 8, 5, 0, -1,
                  -1, 0, 1, 2, 3, 4 };
                  
    int n = arr.Length;
     
    // Function call
    Console.WriteLine(findMinLength(arr));
}
}
 
// This code is contributed by Amit Katiyar

chevron_right


Output: 

4






 

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.