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
๐Ÿ“š The Messy Bookshelf Analogy264810915โœ“ In orderโœ— Messy sectionโœ“ In orderThis section needs reorganizing!The Algorithm in ActionPass 1 (โ†’): Find rightmost element that's too small for its positionPass 2 (โ†): Find leftmost element that's too large for its positionResult: Distance between these boundaries = length to sortโœจ Optimal: O(n) time, O(1) space - no sorting needed!๐ŸŽฏ Key InsightInstead of sorting the entire section, we just need tofind its boundaries by tracking order violations!
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!
Asked in
Google 47 Amazon 38 Microsoft 29 Apple 22
52.3K Views
High Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen