![]() |
VOOZH | about |
Given an unsorted array arr[]. Find the subarray arr[s...e] such that sorting this subarray makes the whole array sorted.
Note: If the given array is already sorted then return [0, 0].
Examples:
Input: arr[] = [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60]
Output: [3, 8]
Explanation: Sorting subarray starting from index 3 and ending at index 8 results in sorted array. Initial array: [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60], Final array: [10, 12, 20, 25, 30, 31, 32, 35, 40, 50, 60](After sorting the bold part).Input: arr[] = [0, 1, 15, 25, 6, 7, 30, 40, 50]
Output: [2, 5]
Explanation: Sorting subarray starting from index 2 and ending at index 5 results in sorted array. Initial array: [0, 1, 15, 25, 6, 7, 30, 40, 50], Final array: [0, 1, 6, 7, 15, 25, 30, 40, 50](After sorting the bold part).Input: arr[] = [30, 20, 10]
Output: [0, 2]
Explanation: We need to sort the whole array to make it sorted
Table of Content
The idea is create an auxiliary array temp[] equal to given array arr[], and sort the temp[] 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, and the indices are [s, e].
2 5
The idea is to check each element’s nearest smaller element to its left and keep track of the maximum element seen so far. This problem mainly becomes a variation of previous smaller element.
2 5
The idea is to find the leftmost and rightmost index that are not following the sorted order, and then find the minimum and maximum element in subarray [left, right]. Thereafter, find the first element in [0, left - 1], which is greater than minimum, and the last element in [end + 1, n], which is smaller than maximum. These two indices are the required answer.
Follow the below given steps:
Below is the implementation of the above approach:
2 5