Shortest Unsorted Continuous Subarray - Problem

Given an integer array nums, you need to find one continuous subarray such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.

Return the length of the shortest such subarray.

Note: The array may already be sorted, in which case the answer is 0.

Input & Output

Example 1 — Basic Unsorted Middle
$ Input: nums = [2,6,4,8,10,9,15]
Output: 5
💡 Note: Need to sort subarray [6,4,8,10,9] from index 1 to 5. After sorting it becomes [4,6,8,9,10], making the whole array [2,4,6,8,9,10,15] which is fully sorted. Length = 5.
Example 2 — Already Sorted
$ Input: nums = [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 — Entire Array Unsorted
$ Input: nums = [5,4,3,2,1]
Output: 5
💡 Note: The entire array is in reverse order. We need to sort the whole array [5,4,3,2,1] to get [1,2,3,4,5]. Length = 5.

Constraints

  • 1 ≤ nums.length ≤ 104
  • -105 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Find Shortest Subarray to SortInput:264810915sortedneeds sortingsortedSubarray to sort: length 5After sorting subarray:246891015Output: 5 (length of shortest subarray to sort)
Understanding the Visualization
1
Input Array
Array with some elements out of order
2
Find Boundaries
Identify the shortest subarray to sort
3
Result
Length of the unsorted subarray
Key Takeaway
🎯 Key Insight: Find the leftmost element that's larger than some element to its right, and the rightmost element that's smaller than some element to its left.
Asked in
Google 42 Amazon 38 Microsoft 25 Facebook 18
197.2K Views
High Frequency
~25 min Avg. Time
6.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