Shortest Unsorted Continuous Subarray
To solve this problem, you need to find the shortest subarray such that if you only sort this subarray, the whole array will be sorted.
Here is the Python solution using a two pointer approach:
- Initialize two pointers,
left
andright
. - Start from the beginning of the array and keep moving right until you find an element that is greater than the next element. Similarly, start from the end of the array and keep moving left until you find an element that is less than the previous element. These two elements are your
left
andright
pointers. - Find the minimum and maximum values in the subarray between
left
andright
. - Extend the subarray to the left until all elements to the left are less than or equal to the minimum in the subarray. Similarly, extend the subarray to the right until all elements to the right are greater than or equal to the maximum in the subarray.
- The length of the subarray between the updated
left
andright
pointers (inclusive) is the shortest subarray that needs to be sorted.
|
|
This code first finds the left
and right
boundaries of the unsorted subarray, and then expands these boundaries if necessary. It returns the length of the subarray that needs to be sorted.