Shortest Unsorted Continuous Subarray (LeetCode 581): Solution and Explanation
Find the shortest continuous piece of nums that, once sorted on its own, leaves the whole array sorted, and return its length. For [2,6,4,8,10,9,15] the piece is [6,4,8,10,9], so the answer is 5. A sorted array gives 0.
Intuition
Sorting a copy and comparing works, but it costs O(n log n). The real question is simpler: which positions are definitely in the wrong place?
A value is in the wrong place if something bigger sits to its left, because that bigger value has to move past it. Scanning left to right with a running max finds every such value, and the last one is the right edge of the piece to sort.
By symmetry, a value is also in the wrong place if something smaller sits to its right. Scanning right to left with a running min finds those, and the leftmost one is the left edge. Everything outside the two edges is already where sorting would put it.
Approach: Two passes with running max and running min
- Set
start = 0andend = -1, so a sorted array returnsend - start + 1 = 0. - Left to right: update
hi = max(hi, nums[i]). Ifnums[i] < hi, setend = i. - Right to left: update
lo = min(lo, nums[i]). Ifnums[i] > lo, setstart = i. - Return
end - start + 1.
Step-by-step example
nums = [2,6,4,8,10,9,15]
- Pass 1 starts with hi = 2. At index 1, 6 becomes the max.
- At index 2, 4 is below the max 6, so end = 2.
- At indexes 3 and 4, 8 and 10 are new maxes. At index 5, 9 is below 10, so end = 5. At index 6, 15 is a new max.
- Pass 2 starts with lo = 15. 9 becomes the min at index 5, and 10 at index 4 is above it, so start = 4.
- 8 at index 3 and 4 at index 2 are new mins. 6 at index 1 is above 4, so start = 1. 2 at index 0 is a new min.
- The answer is end - start + 1 = 5 - 1 + 1 = 5.
Code: Python, Java, C++
1class Solution:
2 def findUnsortedSubarray(self, nums: List[int]) -> int:
3 n = len(nums)
4 start, end = 0, -1
5 hi, lo = nums[0], nums[n - 1]
6 for i in range(1, n):
7 hi = max(hi, nums[i])
8 if nums[i] < hi:
9 end = i
10 for i in range(n - 2, -1, -1):
11 lo = min(lo, nums[i])
12 if nums[i] > lo:
13 start = i
14 return end - start + 11class Solution {
2 public int findUnsortedSubarray(int[] nums) {
3 int n = nums.length;
4 int start = 0, end = -1;
5 int hi = nums[0], lo = nums[n - 1];
6 for (int i = 1; i < n; i++) {
7 hi = Math.max(hi, nums[i]);
8 if (nums[i] < hi) end = i;
9 }
10 for (int i = n - 2; i >= 0; i--) {
11 lo = Math.min(lo, nums[i]);
12 if (nums[i] > lo) start = i;
13 }
14 return end - start + 1;
15 }
16}1class Solution {
2public:
3 int findUnsortedSubarray(vector<int>& nums) {
4 int n = nums.size();
5 int start = 0, end = -1;
6 int hi = nums[0], lo = nums[n - 1];
7 for (int i = 1; i < n; i++) {
8 hi = max(hi, nums[i]);
9 if (nums[i] < hi) end = i;
10 }
11 for (int i = n - 2; i >= 0; i--) {
12 lo = min(lo, nums[i]);
13 if (nums[i] > lo) start = i;
14 }
15 return end - start + 1;
16 }
17};Time and space complexity
O(n)
Two linear passes over the array.
O(1)
Only the running max, running min and two indexes are stored.
Other approaches
Compare with a sorted copy (time O(n log n), space O(n))
Sort a copy of the array. The first and last indexes where the copy and the original differ are the edges of the answer. Short to write and easy to trust.
Monotonic stacks (time O(n), space O(n))
Push indexes on an increasing stack from the left. When a smaller value arrives, every popped index marks a position it has to move past, so the smallest popped index is a candidate left edge. Do the mirror image from the right for the right edge.
Common mistakes
- Stopping at the first descent from each side. In
[1,3,2,2,2]the first descent from the right is at the very end, but the 3 has to move past all three 2s, so the answer is 4, not 2. - Using
<=for the comparison with the running max. Equal values are allowed to stay next to each other, so they must not extend the window. - Starting
startandendat the same value. Then a sorted array returns 1 instead of 0; usestart = 0, end = -1or an explicit check.
Frequently asked questions
Why does the last value below the running max give the right edge?
Any value to the right of that index is at least as large as everything before it, so sorting the prefix up to that index cannot affect it. The value at that index itself is smaller than something before it, so it must be inside the sorted piece.
Can the two passes be merged into one loop?
Yes. Run i from left to right and j = n - 1 - i from right to left inside the same loop, updating the max with nums[i] and the min with nums[j]. It does the same work, just interleaved.
Why is this filed under stacks?
A common O(n) solution uses monotonic stacks to find how far each out-of-order value has to travel. The two-pass version reaches the same edges without the extra memory.