Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted - GeeksforGeeks

13 Dec, 2021
Given an unsorted array arr[0..n-1] of size n, find the minimum length subarray arr[s..e] such that sorting this subarray makes the whole array sorted. Examples: 1) If the input array is [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60], your program should be able to find that the subarray lies between the indexes 3 and 8.2) If the input array is [0, 1, 15, 25, 6, 7, 30, 40, 50], your program should be able to find that the subarray lies between the indexes 2 and 5. 
Solution: 1) Find the candidate unsorted subarray a) Scan from left to right and find the first element which is greater than the next element. Let s be the index of such an element. In the above example 1, s is 3 (index of 30). b) Scan from right to left and find the first element (first in right to left order) which is smaller than the next element (next in right to left order). Let e be the index of such an element. In the above example 1, e is 7 (index of 31).2) Check whether sorting the candidate unsorted subarray makes the complete array sorted or not. If not, then include more elements in the subarray. a) Find the minimum and maximum values in arr[s..e]. Let minimum and maximum values be min and max. min and max for [30, 25, 40, 32, 31] are 25 and 40 respectively. b) Find the first element (if there is any) in arr[0..s-1] which is greater than min, change s to index of this element. There is no such element in above example 1. c) Find the last element (if there is any) in arr[e+1..n-1] which is smaller than max, change e to index of this element. In the above example 1, e is changed to 8 (index of 35)3) Print s and e.Implementation:  
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find the Minimum length Unsorted Subarray,// sorting which makes the complete array sorted#include<bits/stdc++.h>using namespace std; void printUnsorted(int arr[], int n){int s = 0, e = n-1, i, max, min; // step 1(a) of above algofor (s = 0; s < n-1; s++){    if (arr[s] > arr[s+1])    break;}if (s == n-1){    cout << "The complete array is sorted";    return;} // step 1(b) of above algofor(e = n - 1; e > 0; e--){    if(arr[e] < arr[e-1])    break;} // step 2(a) of above algomax = arr[s]; min = arr[s];for(i = s + 1; i <= e; i++){    if(arr[i] > max)    max = arr[i];    if(arr[i] < min)    min = arr[i];} // step 2(b) of above algofor( i = 0; i < s; i++){    if(arr[i] > min)    {    s = i;    break;    }    } // step 2(c) of above algofor( i = n -1; i >= e+1; i--){    if(arr[i] < max)    {    e = i;    break;    }}     // step 3 of above algocout << "The unsorted subarray which"     << " makes the given array" << endl     << "sorted lies between the indices "     << s << " and " << e;return;} int main(){    int arr[] = {10, 12, 20, 30, 25,                 40, 32, 31, 35, 50, 60};    int arr_size = sizeof(arr)/sizeof(arr[0]);    printUnsorted(arr, arr_size);    getchar();    return 0;} // This code is contributed// by Akanksha Rai
// C program to find the Minimum length Unsorted Subarray,// sorting which makes the complete array sorted#include<stdio.h>  void printUnsorted(int arr[], int n){  int s = 0, e = n-1, i, max, min;      // step 1(a) of above algo  for (s = 0; s < n-1; s++)  {    if (arr[s] > arr[s+1])      break;  }  if (s == n-1)  {    printf("The complete array is sorted");    return;  }    // step 1(b) of above algo  for(e = n - 1; e > 0; e--)  {    if(arr[e] < arr[e-1])      break;  }    // step 2(a) of above algo  max = arr[s]; min = arr[s];  for(i = s + 1; i <= e; i++)  {    if(arr[i] > max)      max = arr[i];    if(arr[i] < min)      min = arr[i];  }    // step 2(b) of above algo  for( i = 0; i < s; i++)  {    if(arr[i] > min)    {       s = i;      break;    }       }    // step 2(c) of above algo  for( i = n -1; i >= e+1; i--)  {    if(arr[i] < max)    {      e = i;      break;    }  }         // step 3 of above algo  printf(" The unsorted subarray which makes the given array "         " sorted lies between the indees %d and %d", s, e);  return;}  int main(){  int arr[] = {10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60};  int arr_size = sizeof(arr)/sizeof(arr[0]);  printUnsorted(arr, arr_size);  getchar();  return 0;}
// Java program to find the Minimum length Unsorted Subarray,// sorting which makes the complete array sortedclass Main{    static void printUnsorted(int arr[], int n)    {      int s = 0, e = n-1, i, max, min;               // step 1(a) of above algo      for (s = 0; s < n-1; s++)      {        if (arr[s] > arr[s+1])          break;      }      if (s == n-1)      {        System.out.println("The complete array is sorted");        return;      }             // step 1(b) of above algo      for(e = n - 1; e > 0; e--)      {        if(arr[e] < arr[e-1])          break;      }             // step 2(a) of above algo      max = arr[s]; min = arr[s];      for(i = s + 1; i <= e; i++)      {        if(arr[i] > max)          max = arr[i];        if(arr[i] < min)          min = arr[i];      }             // step 2(b) of above algo      for( i = 0; i < s; i++)      {        if(arr[i] > min)        {           s = i;          break;        }           }             // step 2(c) of above algo      for( i = n -1; i >= e+1; i--)      {        if(arr[i] < max)        {          e = i;          break;        }      }                  // step 3 of above algo      System.out.println(" The unsorted subarray which"+                         " makes the given array sorted lies"+                       "  between the indices "+s+" and "+e);      return;    }           public static void main(String args[])    {      int arr[] = {10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60};      int arr_size = arr.length;      printUnsorted(arr, arr_size);    }}
# Python3 program to find the Minimum length Unsorted Subarray,# sorting which makes the complete array sorteddef printUnsorted(arr, n):    e = n-1    # step 1(a) of above algo    for s in range(0,n-1):        if arr[s] > arr[s+1]:            break             if s == n-1:        print ("The complete array is sorted")        exit()     # step 1(b) of above algo    e= n-1    while e > 0:        if arr[e] < arr[e-1]:            break        e -= 1     # step 2(a) of above algo    max = arr[s]    min = arr[s]    for i in range(s+1,e+1):        if arr[i] > max:            max = arr[i]        if arr[i] < min:            min = arr[i]                 # step 2(b) of above algo    for i in range(s):        if arr[i] > min:            s = i            break     # step 2(c) of above algo    i = n-1    while i >= e+1:        if arr[i] < max:            e = i            break        i -= 1         # step 3 of above algo    print ("The unsorted subarray which makes the given array")    print ("sorted lies between the indexes %d and %d"%( s, e)) arr = [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60]arr_size = len(arr)printUnsorted(arr, arr_size) # This code is contributed by Shreyanshi Arun
// C# program to find the Minimum length Unsorted Subarray,// sorting which makes the complete array sorted using System; class GFG{    static void printUnsorted(int []arr, int n)    {    int s = 0, e = n-1, i, max, min;             // step 1(a) of above algo    for (s = 0; s < n-1; s++)    {        if (arr[s] > arr[s+1])        break;    }    if (s == n-1)    {        Console.Write("The complete " +                            "array is sorted");        return;    }             // step 1(b) of above algo    for(e = n - 1; e > 0; e--)    {        if(arr[e] < arr[e-1])        break;    }             // step 2(a) of above algo    max = arr[s]; min = arr[s];         for(i = s + 1; i <= e; i++)    {        if(arr[i] > max)            max = arr[i];                 if(arr[i] < min)            min = arr[i];    }             // step 2(b) of above algo    for( i = 0; i < s; i++)    {        if(arr[i] > min)        {            s = i;            break;        }        }             // step 2(c) of above algo    for( i = n -1; i >= e+1; i--)    {        if(arr[i] < max)        {            e = i;            break;        }    }                 // step 3 of above algo    Console.Write(" The unsorted subarray which"+            " makes the given array sorted lies \n"+              " between the indices "+s+" and "+e);    return;    }             public static void Main()    {        int []arr = {10, 12, 20, 30, 25, 40,                                32, 31, 35, 50, 60};        int arr_size = arr.Length;                 printUnsorted(arr, arr_size);    }} // This code contributed by Sam007
<?php// PHP program to find the Minimum length Unsorted Subarray,// sorting which makes the complete array sortedfunction printUnsorted(&$arr, $n){    $s = 0;    $e = $n - 1;         // step 1(a) of above algo    for ($s = 0; $s < $n - 1; $s++)    {        if ($arr[$s] > $arr[$s + 1])        break;    }    if ($s == $n - 1)    {        echo "The complete array is sorted";        return;    }         // step 1(b) of above algo    for($e = $n - 1; $e > 0; $e--)    {        if($arr[$e] < $arr[$e - 1])        break;    }         // step 2(a) of above algo    $max = $arr[$s];    $min = $arr[$s];    for($i = $s + 1; $i <= $e; $i++)    {        if($arr[$i] > $max)            $max = $arr[$i];        if($arr[$i] < $min)            $min = $arr[$i];    }         // step 2(b) of above algo    for( $i = 0; $i < $s; $i++)    {        if($arr[$i] > $min)        {            $s = $i;            break;        }        }         // step 2(c) of above algo    for( $i = $n - 1; $i >= $e + 1; $i--)    {        if($arr[$i] < $max)        {            $e = $i;            break;        }    }             // step 3 of above algo    echo " The unsorted subarray which makes " .                     "the given array " . "\n" .            " sorted lies between the indees " .                              $s . " and " . $e;    return;} // Driver code$arr = array(10, 12, 20, 30, 25, 40,             32, 31, 35, 50, 60);$arr_size = sizeof($arr);printUnsorted($arr, $arr_size); // This code is contributed// by ChitraNayal?>
<script> // Javascript program to find the Minimum length Unsorted Subarray, // sorting which makes the complete array sorted         function printUnsorted(arr,n)    {        let s = 0, e = n-1, i, max, min;        // step 1(a) of above algo        for (s = 0; s < n-1; s++)        {            if (arr[s] > arr[s+1])                break;        }        if (s == n-1)        {            document.write("The complete array is sorted");            return;        }        // step 1(b) of above algo        for(e = n - 1; e > 0; e--)        {            if(arr[e] < arr[e-1])                break;        }        // step 2(a) of above algo        max = arr[s]; min = arr[s];        for(i = s + 1; i <= e; i++)        {            if(arr[i] > max)                max = arr[i];            if(arr[i] < min)                min = arr[i];        }        // step 2(b) of above algo        for( i = 0; i < s; i++)        {            if(arr[i] > min)            {                s = i;                break;            }        }        // step 2(c) of above algo        for( i = n -1; i >= e+1; i--)        {            if(arr[i] < max)            {                e = i;                break;            }        }        // step 3 of above algo        document.write(" The unsorted subarray which"+                         " makes the given array sorted lies"+                       "  between the indees "+s+" and "+e);        return;    }    let arr=[10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60];    let arr_size = arr.length;    printUnsorted(arr, arr_size);         // This code is contributed by avanitrachhadiya2155     </script>
Output :  
 The unsorted subarray which makes the given array 
sorted lies between the indees 3 and 8
Time Complexity: O(n) 
YouTubeGeeksforGeeks507K subscribersMinimum length Unsorted Subarray, sorting which makes the array sorted | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=p7rnuGsau6g" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem. 
ukasp
Akanksha_Rai
avanitrachhadiya2155
singhalrishabh0904
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Arrays in C/C++
Write a program to reverse an array or string
Program for array rotation
Largest Sum Contiguous Subarray