Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted
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 :
#include <bits/stdc++.h>
using namespace std;
// function performing calculation
int minLength(vector<int>& arr)
{
// temporary array equal to given array
vector<int> temp = arr;
// sorting the temporary array
sort(temp.begin(), temp.end());
// initializing indices
int s = 0, e = 0;
// checking the unequal element from start and storing
// it in s variable
for (int i = 0; i < arr.size(); i++) {
if (arr[i] != temp[i]) {
s = i;
break;
}
}
// checking the unequal element from end and storing it
// in e variable
for (int i = arr.size() - 1; i >= 0; i--) {
if (arr[i] != temp[i]) {
e = i;
break;
}
}
// returning minimum length
return (e - s + 1);
}
// driver function
int main()
{
// given array arr
vector<int> arr
= { 10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60 };
// calling the function performing calculation and
// printing the result
cout << "Minimum length of subarray is : "
<< minLength(arr);
return 0;
}
import java.util.*;
public class GFG {
// function performing calculation
public static int minLength(ArrayList<Integer> arr) {
// temporary array equal to given array
ArrayList<Integer> temp = new ArrayList<Integer>(arr);
// sorting the temporary array
Collections.sort(temp);
// initializing indices
int s = 0, e = 0;
// checking the unequal element from start and storing
// it in s variable
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i) != temp.get(i)) {
s = i;
break;
}
}
// checking the unequal element from end and storing it
// in e variable
for (int i = arr.size() - 1; i >= 0; i--) {
if (arr.get(i) != temp.get(i)) {
e = i;
break;
}
}
// returning minimum length
return (e - s + 1);
}
// driver function
public static void main(String[] args) {
// given array arr
ArrayList<Integer> arr = new ArrayList<Integer>(
Arrays.asList(10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60)
);
// calling the function performing calculation and
// printing the result
System.out.println("Minimum length of subarray is : " + minLength(arr));
}
}
# importing the library
from typing import List
# function performing calculation
def minLength(arr: List[int]) -> int:
# temporary array equal to given array
temp = arr[:]
# sorting the temporary array
temp.sort()
# initializing indices
s = 0
e = 0
# checking the unequal element from start and storing
# it in s variable
for i in range(len(arr)):
if arr[i] != temp[i]:
s = i
break
# checking the unequal element from end and storing it
# in e variable
for i in range(len(arr)-1, -1, -1):
if arr[i] != temp[i]:
e = i
break
# returning minimum length
return (e - s + 1)
# driver function
if __name__ == '__main__':
# given array arr
arr = [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60]
# calling the function performing calculation and
# printing the result
print("Minimum length of subarray is : ", minLength(arr))
# This code is contributed by divyansh2212
using System;
using System.Linq;
class Program
{
//function performing calculations
static int MinLength(int[] arr)
{
//temporary array equal to given array
int[] temp = arr.ToArray();
//sorting the temporary array
Array.Sort(temp);
//initializing indices
int s = 0;
int e = 0;
//checking the unequal element from start and storing it in s variable
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] != temp[i])
{
s = i;
break;
}
}
//checking the unequal elements from end and storing it in e variable
for (int i = arr.Length - 1; i >= 0; i--)
{
if (arr[i] != temp[i])
{
e = i;
break;
}
}
//returning minimum length
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));
}
}
//This code is contributed by snehalsalokhe
// function performing calculation
function minLength(arr)
{
// temporary array equal to given array
let temp = [];
for(let i=0;i<arr.length;i++)
{
temp.push(arr[i]);
}
// sorting the temporary array
temp.sort();
// initializing indices
let s = 0, e = 0;
// checking the unequal element from start and storing
// it in s variable
for (let i = 0; i < arr.length; i++) {
if (arr[i] != temp[i]) {
s = i;
break;
}
}
// checking the unequal element from end and storing it
// in e variable
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] != temp[i]) {
e = i;
break;
}
}
// returning minimum length
return (e - s + 1);
}
// driver function
// given array arr
let arr = [ 10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60 ];
// calling the function performing calculation and
// printing the result
console.log("Minimum length of subarray is : "
+ minLength(arr));
// This code is contributed by akashish__
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:
Intuition
For each index calculate the nearest smaller value to it’s left. Let’s say the current index is i and the index of the nearest smaller to left is j. There exists two cases after we find the nearest smaller to left.
Case 1:
If i-j>1 then definitely there exists an element between indices i and j which is greater than nums[i]. So in this case update lidx=min(lidx,j) and ridx=i as the current value has to be moved to the left and hecne the array from nums[j+1..i] has to be sorted. lidx+1 denotes the starting point of the array which has to be sorted and ridx dentoes the end of the array which has to be sorted and hence at the end length of the array to be sorted will be ridx-lidx. I am taking minimum as I have to find the first index from the left from where I have to start sorting the array.
Case 2:
if i-j<=1, then the nearest smaller to left of this element occurs just occurs before this element i.e. at i-1 which does not violate the condition of a non-decreasing array but, there might be a case where there would be greater element than nums[i] occuring to it’s left and in that case the position of current element nums[i] would not be right in the final array.
Keep measure of the maximum element of the array before the current element. if the maximum element of the array is greater than nums[i] then definitely we have update the end of the array as the this element has to be shifted so that the greater element can come sit at this index i.
But if nums[i] == maxi then it may happend that maxi might not occur just before this it may occur at indices [0..i-2] so just check if the stack top( which stores the index of the nearest smaller to right if equal to maxi) and if it is no need to update the end of the array and if it is not then update the ridx=i-1, (i-1 because let’s say if the array is [3,2,3] then I have to just sort the subarray [a[0],a[1]] and not include a[2] as it is already at the right position according to the final sorted array).
#include <bits/stdc++.h>
using namespace std;
// function performing calculation
int minLength(vector<int>& arr)
{
int n = arr.size();
int lidx = INT_MAX, ridx = INT_MAX;
int maxi = INT_MIN;
stack<int> st;
for (int i = 0; i < n; ++i) {
while (!st.empty() and arr[i] < arr[st.top()])
st.pop();
if (!st.empty()) {
if (i - st.top() > 1) {
lidx = min(lidx, st.top());
ridx = i;
}
else {
if (arr[i] < maxi)
ridx = i;
else if (arr[st.top()] != maxi)
ridx = i - 1;
}
}
else if (i != 0) {
lidx = -1;
ridx = i;
}
maxi = max(maxi, arr[i]);
st.push(i);
}
return ridx - lidx;
}
// driver function
int main()
{
// given array arr
vector<int> arr
= { 10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60 };
// calling the function performing calculation and
// printing the result
cout << "Minimum length of subarray is : "
<< minLength(arr);
return 0;
}
import java.util.Stack;
public class Main {
public static int minLength(int[] arr)
{
int n = arr.length;
int lidx = Integer.MAX_VALUE;
int ridx = Integer.MAX_VALUE;
int maxi = Integer.MIN_VALUE;
Stack<Integer> st = new Stack<>();
for (int i = 0; i < n; ++i) {
while (!st.isEmpty() && arr[i] < arr[st.peek()])
st.pop();
if (!st.isEmpty()) {
if (i - st.peek() > 1) {
lidx = Math.min(lidx, st.peek());
ridx = i;
}
else {
if (arr[i] < maxi)
ridx = i;
else if (arr[st.peek()] != maxi)
ridx = i - 1;
}
}
else if (i != 0) {
lidx = -1;
ridx = i;
}
maxi = Math.max(maxi, arr[i]);
st.push(i);
}
return ridx - lidx;
}
public static void main(String[] args)
{
// given array arr
int[] arr = { 10, 12, 20, 30, 25, 40,
32, 31, 35, 50, 60 };
// calling the function performing calculation and
// printing the result
System.out.println(
"Minimum length of subarray is : "
+ minLength(arr));
}
}
def min_length(arr):
n = len(arr)
lidx = float('inf')
ridx = float('inf')
maxi = float('-inf')
st = []
for i in range(n):
while st and arr[i] < arr[st[-1]]:
st.pop()
if st:
if i - st[-1] > 1:
lidx = min(lidx, st[-1])
ridx = i
else:
if arr[i] < maxi:
ridx = i
elif arr[st[-1]] != maxi:
ridx = i - 1
elif i != 0:
lidx = -1
ridx = i
maxi = max(maxi, arr[i])
st.append(i)
return ridx - lidx
# given array arr
arr = [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60]
# calling the function performing calculation and printing the result
print("Minimum length of subarray is:", min_length(arr))
function minLength(arr) {
let n = arr.length;
let lidx = Infinity;
let ridx = Infinity;
let maxi = -Infinity;
let st = [];
for (let i = 0; i < n; ++i) {
while (st.length && arr[i] < arr[st[st.length - 1]])
st.pop();
if (st.length) {
if (i - st[st.length - 1] > 1) {
lidx = Math.min(lidx, st[st.length - 1]);
ridx = i;
} else {
if (arr[i] < maxi)
ridx = i;
else if (arr[st[st.length - 1]] != maxi)
ridx = i - 1;
}
} else if (i != 0) {
lidx = -1;
ridx = i;
}
maxi = Math.max(maxi, arr[i]);
st.push(i);
}
return ridx - lidx;
}
// given array arr
let arr = [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60];
// calling the function performing calculation and printing the result
console.log("Minimum length of subarray is:", minLength(arr));
<?php
function minLength($arr) {
$n = count($arr);
$lidx = PHP_INT_MAX;
$ridx = PHP_INT_MAX;
$maxi = PHP_INT_MIN;
$st = [];
for ($i = 0; $i < $n; ++$i) {
while (!empty($st) && $arr[$i] < $arr[end($st)])
array_pop($st);
if (!empty($st)) {
if ($i - end($st) > 1) {
$lidx = min($lidx, end($st));
$ridx = $i;
} else {
if ($arr[$i] < $maxi)
$ridx = $i;
elseif ($arr[end($st)] != $maxi)
$ridx = $i - 1;
}
} elseif ($i != 0) {
$lidx = -1;
$ridx = $i;
}
$maxi = max($maxi, $arr[$i]);
array_push($st, $i);
}
return $ridx - $lidx;
}
// given array arr
$arr = [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60];
// calling the function performing calculation and printing the result
echo "Minimum length of subarray is: " . minLength($arr);
?>
Time Complexity : O(N) , where N is the size of given array
Space Complexity : O(N) , Space for stack .
Approach 3:
- 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++ 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 algo
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;
}
// 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
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;
}
// 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 sorted
import java.io.*;
class 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 sorted
def 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
<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>
<?php
// PHP program to find the Minimum length Unsorted Subarray,
// sorting which makes the complete array sorted
function 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
?>
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.
Contact Us