Find shortest subarray to restore order
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates array manipulation and algorithmic problem-solving skills, focusing on understanding how local subarray sorting affects global order, edge-case reasoning (already-sorted arrays, duplicates, strictly decreasing sequences), and complexity analysis within the Coding & Algorithms domain.
Constraints
- 1 <= nums.length <= 10^4 (function also handles the empty array)
- -10^5 <= nums[i] <= 10^5
- The array may contain duplicates.
Examples
Input: ([2, 6, 4, 8, 10, 9, 15],)
Expected Output: 5
Explanation: Sorting the subarray [6, 4, 8, 10, 9] (indices 1..5) makes the array non-decreasing; length 5.
Input: ([1, 2, 3, 4],)
Expected Output: 0
Explanation: Already non-decreasing, so no subarray needs sorting.
Input: ([1],)
Expected Output: 0
Explanation: A single element is trivially sorted.
Input: ([],)
Expected Output: 0
Explanation: An empty array is trivially sorted.
Input: ([2, 1],)
Expected Output: 2
Explanation: The whole array is out of order; sorting both elements is required.
Input: ([5, 4, 3, 2, 1],)
Expected Output: 5
Explanation: Strictly decreasing array: the entire array must be sorted.
Input: ([1, 3, 2, 2, 2],)
Expected Output: 4
Explanation: The 3 must move past the trailing 2s; window spans indices 1..4 -> length 4.
Input: ([1, 1, 1, 1],)
Expected Output: 0
Explanation: All equal, already non-decreasing.
Input: ([-1, -5, -3, 0, 2],)
Expected Output: 3
Explanation: Sorting [-1, -5, -3] (indices 0..2) fixes the array; length 3, handling negatives.
Input: ([1, 2, 3, 3, 3, 2],)
Expected Output: 4
Explanation: The trailing 2 is smaller than earlier 3s; window spans indices 2..5 -> length 4, handling duplicates.
Hints
- An element belongs in the unsorted window if it is smaller than some element to its left, or larger than some element to its right.
- Scan left-to-right tracking the running maximum to find the rightmost index that is out of order; scan right-to-left tracking the running minimum to find the leftmost.
- If no element is ever out of order during the left-to-right scan, the array is already sorted and the answer is 0.