Problem 513
Shortest Unsorted Continuous Subarray
Medium · 20 pts · Array, Two Pointers, Sorting
Problem
Find the shortest block of consecutive elements such that, if you sort just that block in non-decreasing order, the whole array becomes sorted. Print its length, or 0 if the array is already sorted. Comparing the array with a sorted copy works in O(N log N); a linear pass that tracks the running maximum from the left and the running minimum from the right finds the two ends directly.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1].
Output
Print the length of the shortest such subarray.
Constraints
1 <= N <= 100000; -100000 <= A[i] <= 100000
Example input
7 2 6 4 8 10 9 15
Example output
5
Explanation
In 2 6 4 8 10 9 15, sorting the block 6 4 8 10 9 gives 4 6 8 9 10, and the whole array becomes 2 4 6 8 9 10 15. That block has length 5, and no shorter block works.