The Shortest Unsorted Continuous Subarray interview question asks you to find the shortest subarray such that if you sort it, the entire array becomes sorted. Equivalently, find the smallest window [l, r] where sorting nums[l..r] results in the whole array being non-decreasing. Return r - l + 1, or 0 if the array is already sorted.
Microsoft, Meta, Amazon, Google, Bloomberg, and Adobe ask this problem because it has an elegant O(n) solution that avoids sorting. The sorted comparison approach is O(n log n); the O(n) approach finds the leftmost element that is out of position and the rightmost element that is out of position using a single forward and backward scan with running min/max. It tests candidates' ability to reduce an apparently sorting problem to a linear scan.
The pattern is two-pass linear scan with running max/min. Forward pass: find the last index right where nums[i] < running_max_from_left. Backward pass: find the first index left where nums[i] > running_min_from_right. If no such index is found in either pass, the array is sorted (return 0). Otherwise, return right - left + 1. This is O(n) with O(1) space.
Array: [2, 6, 4, 8, 10, 9, 15].
Forward pass (running max from left):
Backward pass (running min from right):
Answer: right - left + 1 = 5 - 1 + 1 = 5 (subarray [6, 4, 8, 10, 9]).
sorted(nums) and comparing element by element — O(n log n) and uses extra space; the O(n) approach is expected.left and right may need to extend beyond the first and last unsorted elements.right - left instead of right - left + 1 (off-by-one in subarray length).For the Shortest Unsorted Continuous Subarray coding problem, the two-pointer array monotonic scan interview pattern is the O(n) solution. The key insight: right = last position where the running maximum from the left exceeds the current element; left = first position where the running minimum from the right is less than the current element. Meta and Adobe interviewers test the distinction between the sorting approach and the O(n) approach. Know both — state the O(n log n) sorting approach first, then optimize to O(n). This establishes analytical thinking before diving into code.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Max Chunks To Make Sorted | Medium | Solve | |
| The Number of Weak Characters in the Game | Medium | Solve | |
| Max Chunks To Make Sorted II | Hard | Solve | |
| Create Maximum Number | Hard | Solve | |
| Maximum Width Ramp | Medium | Solve |