Shortest Unsorted Continuous Subarray - Problem
You're given an integer array that's almost sorted, but not quite. Your task is to find the shortest continuous subarray that, if sorted, would make the entire array perfectly sorted in non-decreasing order.
Think of it as finding the "messy middle" of an otherwise organized array. For example, in [2, 6, 4, 8, 10, 9, 15], if we sort just the subarray [6, 4, 8, 10, 9] to get [4, 6, 8, 9, 10], the entire array becomes sorted: [2, 4, 6, 8, 9, 10, 15].
Goal: Return the length of this shortest subarray. If the array is already sorted, return 0.
Input & Output
example_1.py โ Standard Case
$
Input:
[2, 6, 4, 8, 10, 9, 15]
โบ
Output:
5
๐ก Note:
The subarray [6, 4, 8, 10, 9] needs to be sorted. When sorted to [4, 6, 8, 9, 10], the entire array becomes [2, 4, 6, 8, 9, 10, 15] which is sorted.
example_2.py โ Already Sorted
$
Input:
[1, 2, 3, 4]
โบ
Output:
0
๐ก Note:
The array is already sorted in non-decreasing order, so no subarray needs to be sorted. Return 0.
example_3.py โ Reverse Sorted
$
Input:
[3, 2, 1]
โบ
Output:
3
๐ก Note:
The entire array needs to be sorted since it's in reverse order. The shortest subarray is the entire array itself with length 3.
Constraints
- 1 โค nums.length โค 104
- -105 โค nums[i] โค 105
- Follow-up: Can you solve it in O(n) time complexity?
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Problem
The array is mostly sorted but has a 'messy middle' section
2
Find Left Boundary
Scan right and mark where elements are smaller than expected
3
Find Right Boundary
Scan left and mark where elements are larger than expected
4
Calculate Length
The distance between boundaries gives us the answer
Key Takeaway
๐ฏ Key Insight: We don't need to actually sort anything - just find where the order breaks down by tracking the rightmost "too small" element and leftmost "too large" element in a single pass!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code