Skip to content
Problem 581 · LeetCode 581(opens in a new tab)

Shortest Unsorted Continuous Subarray

MediumArrays

You are given an integer array nums. Choose one run of neighbouring positions so that sorting only that run, in non-decreasing order, leaves the whole array sorted.

Return the length of the shortest run that works. If the array is already sorted, return 0.

Example 1

Input:  nums = [1, 5, 3, 4, 2, 6]
Output: 4
Why:    sorting [5, 3, 4, 2] gives 1 2 3 4 5 6
2 more examples and the constraints

Example 2

Input:  nums = [3, 3, 7, 9]
Output: 0
Why:    equal neighbours are allowed; it is already sorted

Example 3

Input:  nums = [4, 2]
Output: 2
Why:    both values have to swap places

Constraints

  • 1 ≤ length of nums ≤ 10,000
  • −100,000 ≤ nums[i] ≤ 100,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Compare with a sorted copyO(n log n)
  2. Running max and minO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 valuesVerdict
Compare with a sorted copyO(n log n)
Fine; easy to get right
Running max and minO(n)
Best; answers the follow-up

n = length of nums.

Edge cases to test

  • Already sorted. [3, 3, 7, 9] gives 0; equal neighbours are fine.
  • A single value. [7] is sorted: 0.
  • Fully reversed. [5, 4, 3, 2, 1] needs the whole array: 5.
  • Duplicates at the edges of the run. In [1, 3, 2, 2, 2], every 2 is below the 3 before it, so the run is [3, 2, 2, 2]: 4.

Common mistakes

  • Comparing only neighbours: in [1, 5, 3, 4, 2, 6] the 4 is bigger than the 3 before it but still out of place.
  • Using ≤ instead of < in the left-to-right check, so equal values are moved for no reason.
  • Returning end − start + 1 with bad defaults, so a sorted array gives 1 or a negative number.

How to talk through it

  1. 1Clarify. Is non-decreasing order the goal, so equal values are fine? Should a sorted array return 0?
  2. 2Give the simple answer. Sort a copy and find the first and last positions that differ: O(n log n).
  3. 3Define out of place. A value must move if something bigger is before it or something smaller is after it.
  4. 4Two passes. A running max from the left finds the end; a running min from the right finds the start.
  5. 5Test out loud. Try a sorted array, a reversed one, one value, and duplicates next to the run.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?