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
Shortest Unsorted Continuous Subarray INPUT nums = [2,6,4,8,10,9,15] 2 0 6 1 4 2 8 3 10 4 9 5 15 6 Sorted position Unsorted subarray Sorted Array: [2,4,6,8,9,10,15] Subarray to sort indices 1 to 5 ALGORITHM STEPS 1 Find Right Boundary Scan left-to-right, track max End = last i where nums[i] < max 2 Find Left Boundary Scan right-to-left, track min Start = last i where nums[i] > min 3 Calculate Length Length = end - start + 1 4 Edge Case If already sorted, return 0 Trace: Left scan: max=2,6,6,8,10,10,15 end updates: 2,5 (final=5) Right scan: min=15,9,9,8,4,4,2 start updates: 4,2,1 (final=1) FINAL RESULT 2 6 4 8 10 9 15 5 elements OUTPUT 5 Calculation: start = 1, end = 5 length = 5 - 1 + 1 = 5 OK - Verified! Sort [6,4,8,10,9] to fix array Key Insight: The optimal O(n) solution uses two passes: scan left-to-right tracking maximum to find the right boundary (where elements are smaller than the max seen), and right-to-left tracking minimum to find the left boundary (where elements are larger than the min seen). This identifies elements that are out of their sorted position. TutorialsPoint - Shortest Unsorted Continuous Subarray | Optimal Solution O(n)
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