Find Minimum Length Unsorted SubArray | Programming Tutorials

preview_player
Показать описание

Given an array of unsorted integers. We have to write a code to find minimum length subarray such that if we sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.

We have to return the shortest subarray length.

OR

Find the minimum length unsorted subarray sorting which makes the complete array sorted.

For example -

Example 1:

Input: {0, 2, 5, 4, 9, 6, 12}
Output: 4

Minimum length unsorted SubArray is {5, 4, 9, 6}.
If we sort this subarray in ascending order,
then the whole array will be sorted in ascending order.


Example 2:

Input: {1, 5, 3, 8, 10, 9, 13]
Output: 5

We need to sort this subarray {5, 3, 8, 10, 9} in ascending order to
make the whole array sorted.

Рекомендации по теме
Комментарии
Автор

this fails for this scenario - int[] a={4, 6, 23, 26, 0, 8, 24, 35, 39};
Please do recheck and let me know if Im wrong

rajasekharreddy
Автор

can we sole this problem with this approach. Iknow the time complexity has been increased but juts check it whether is this approach is proper

public class MinimunLenthofUnsortedArray {
public static void main(String[] args) {
int arr[] = { 1, 5, 3, 8, 10, 9, 13 };
int start = 0;
int end = 0;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
start = i;
break;

}
}
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] < arr[i + 1]) {
end = i;

}
}
System.out.println(end - start + 1);
}
}

yadnyeshrane