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.
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.