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:
- 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 indexes 3 and 8.
- 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 indexes 2 and 5.
Approach 1:
Idea/Intuition :
Make a temporary array same as the given array ,sort the temporary array . Now check
from starting at which index the element of the given array and temporary array are
unequal and store it in temporary variable s . Repeat the above From the end and store
the index at another temporary variable e . The length e-s+1 is the length of smallest
unequal subarray .
Algorithm :
- Declare a temporary array temp same as given array arr.
- Sort the temporary array .
- Initialize variable s with 0 and e with 0.
- Checking the unequal element from start and storing it in s variable .
- Checking the equal element from end and storing it in e variable.
- Returning (e-s+1) .
- Printing the result .
Below is the implementation of above approach .
Code :
C++
#include <bits/stdc++.h>
using namespace std;
int minLength(vector< int >& arr)
{
vector< int > temp = arr;
sort(temp.begin(), temp.end());
int s = 0, e = 0;
for ( int i = 0; i < arr.size(); i++) {
if (arr[i] != temp[i]) {
s = i;
break ;
}
}
for ( int i = arr.size() - 1; i >= 0; i--) {
if (arr[i] != temp[i]) {
e = i;
break ;
}
}
return (e - s + 1);
}
int main()
{
vector< int > arr
= { 10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60 };
cout << "Minimum length of subarray is : "
<< minLength(arr);
return 0;
}
|
Python3
from typing import List
def minLength(arr: List [ int ]) - > int :
temp = arr[:]
temp.sort()
s = 0
e = 0
for i in range ( len (arr)):
if arr[i] ! = temp[i]:
s = i
break
for i in range ( len (arr) - 1 , - 1 , - 1 ):
if arr[i] ! = temp[i]:
e = i
break
return (e - s + 1 )
if __name__ = = '__main__' :
arr = [ 10 , 12 , 20 , 30 , 25 , 40 , 32 , 31 , 35 , 50 , 60 ]
print ( "Minimum length of subarray is : " , minLength(arr))
|
C#
using System;
using System.Linq;
class Program
{
static int MinLength( int [] arr)
{
int [] temp = arr.ToArray();
Array.Sort(temp);
int s = 0;
int e = 0;
for ( int i = 0; i < arr.Length; i++)
{
if (arr[i] != temp[i])
{
s = i;
break ;
}
}
for ( int i = arr.Length - 1; i >= 0; i--)
{
if (arr[i] != temp[i])
{
e = i;
break ;
}
}
return e - s + 1;
}
static void Main( string [] args)
{
int [] arr = new int [] { 10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60 };
Console.WriteLine( "Minimum length of subarray is : " + MinLength(arr));
}
}
|
Java
import java.util.*;
public class GFG {
public static int minLength(ArrayList<Integer> arr) {
ArrayList<Integer> temp = new ArrayList<Integer>(arr);
Collections.sort(temp);
int s = 0 , e = 0 ;
for ( int i = 0 ; i < arr.size(); i++) {
if (arr.get(i) != temp.get(i)) {
s = i;
break ;
}
}
for ( int i = arr.size() - 1 ; i >= 0 ; i--) {
if (arr.get(i) != temp.get(i)) {
e = i;
break ;
}
}
return (e - s + 1 );
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>(
Arrays.asList( 10 , 12 , 20 , 30 , 25 , 40 , 32 , 31 , 35 , 50 , 60 )
);
System.out.println( "Minimum length of subarray is : " + minLength(arr));
}
}
|
Javascript
function minLength(arr)
{
let temp = [];
for (let i=0;i<arr.length;i++)
{
temp.push(arr[i]);
}
temp.sort();
let s = 0, e = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] != temp[i]) {
s = i;
break ;
}
}
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] != temp[i]) {
e = i;
break ;
}
}
return (e - s + 1);
}
let arr = [ 10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60 ];
console.log( "Minimum length of subarray is : "
+ minLength(arr));
|
Output
Minimum length of subarray is : 6
Time Complexity : O(NLog(N)) , where N is the size of given array
Space Complexity : O(N) , Space for temporary array temp .
Approach 2:
- Find the candidate unsorted subarray
- 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).
- 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).
- Check whether sorting the candidate unsorted subarray makes the complete array sorted or not. If not, then include more elements in the subarray.
- 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.
- 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.
- 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)
- Print s and e.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
void printUnsorted( int arr[], int n)
{
int s = 0, e = n-1, i, max, min;
for (s = 0; s < n-1; s++)
{
if (arr[s] > arr[s+1])
break ;
}
if (s == n-1)
{
cout << "The complete array is sorted" ;
return ;
}
for (e = n - 1; e > 0; e--)
{
if (arr[e] < arr[e-1])
break ;
}
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];
}
for ( i = 0; i < s; i++)
{
if (arr[i] > min)
{
s = i;
break ;
}
}
for ( i = n -1; i >= e+1; i--)
{
if (arr[i] < max)
{
e = i;
break ;
}
}
cout << "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;
}
|
C
#include<stdio.h>
void printUnsorted( int arr[], int n)
{
int s = 0, e = n-1, i, max, min;
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 ;
}
for (e = n - 1; e > 0; e--)
{
if (arr[e] < arr[e-1])
break ;
}
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];
}
for ( i = 0; i < s; i++)
{
if (arr[i] > min)
{
s = i;
break ;
}
}
for ( i = n -1; i >= e+1; i--)
{
if (arr[i] < max)
{
e = i;
break ;
}
}
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
import java.io.*;
class Main
{
static void printUnsorted( int arr[], int n)
{
int s = 0 , e = n- 1 , i, max, min;
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 ;
}
for (e = n - 1 ; e > 0 ; e--)
{
if (arr[e] < arr[e- 1 ])
break ;
}
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];
}
for ( i = 0 ; i < s; i++)
{
if (arr[i] > min)
{
s = i;
break ;
}
}
for ( i = n - 1 ; i >= e+ 1 ; i--)
{
if (arr[i] < max)
{
e = i;
break ;
}
}
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
def printUnsorted(arr, n):
e = n - 1
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()
e = n - 1
while e > 0 :
if arr[e] < arr[e - 1 ]:
break
e - = 1
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]
for i in range (s):
if arr[i] > min :
s = i
break
i = n - 1
while i > = e + 1 :
if arr[i] < max :
e = i
break
i - = 1
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)
|
C#
using System;
class GFG
{
static void printUnsorted( int []arr, int n)
{
int s = 0, e = n-1, i, max, min;
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 ;
}
for (e = n - 1; e > 0; e--)
{
if (arr[e] < arr[e-1])
break ;
}
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];
}
for ( i = 0; i < s; i++)
{
if (arr[i] > min)
{
s = i;
break ;
}
}
for ( i = n -1; i >= e+1; i--)
{
if (arr[i] < max)
{
e = i;
break ;
}
}
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);
}
}
|
PHP
<?php
function printUnsorted(& $arr , $n )
{
$s = 0;
$e = $n - 1;
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 ;
}
for ( $e = $n - 1; $e > 0; $e --)
{
if ( $arr [ $e ] < $arr [ $e - 1])
break ;
}
$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 ];
}
for ( $i = 0; $i < $s ; $i ++)
{
if ( $arr [ $i ] > $min )
{
$s = $i ;
break ;
}
}
for ( $i = $n - 1; $i >= $e + 1; $i --)
{
if ( $arr [ $i ] < $max )
{
$e = $i ;
break ;
}
}
echo " The unsorted subarray which makes " .
"the given array " . "\n" .
" sorted lies between the indees " .
$s . " and " . $e ;
return ;
}
$arr = array (10, 12, 20, 30, 25, 40,
32, 31, 35, 50, 60);
$arr_size = sizeof( $arr );
printUnsorted( $arr , $arr_size );
?>
|
Javascript
<script>
function printUnsorted(arr,n)
{
let s = 0, e = n-1, i, max, min;
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 ;
}
for (e = n - 1; e > 0; e--)
{
if (arr[e] < arr[e-1])
break ;
}
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];
}
for ( i = 0; i < s; i++)
{
if (arr[i] > min)
{
s = i;
break ;
}
}
for ( i = n -1; i >= e+1; i--)
{
if (arr[i] < max)
{
e = i;
break ;
}
}
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);
</script>
|
Output
The unsorted subarray which makes the given array
sorted lies between the indices 3 and 8
Time Complexity : O(n)
Auxiliary Space : O(1)
Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
21 Mar, 2023
Like Article
Save Article