Shortest Subarray to be Removed to Make Array Sorted - Problem
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
Return the length of the shortest subarray to remove.
A subarray is a contiguous subsequence of the array.
Input & Output
Example 1 — Middle Elements Out of Order
$
Input:
arr = [1,2,3,10,4,2,3,5]
›
Output:
3
💡 Note:
Remove subarray [10,4,2] to get [1,2,3,3,5] which is non-decreasing. Minimum length is 3.
Example 2 — Remove Prefix
$
Input:
arr = [5,4,3,2,1]
›
Output:
4
💡 Note:
Remove [5,4,3,2] to keep [1], or remove [4,3,2,1] to keep [5]. Both give length 4.
Example 3 — Already Sorted
$
Input:
arr = [1,2,3,4]
›
Output:
0
💡 Note:
Array is already non-decreasing, so no elements need to be removed.
Constraints
- 1 ≤ arr.length ≤ 105
- 0 ≤ arr[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Array [1,2,3,10,4,2,3,5] with unsorted middle section
2
Find Boundaries
Identify sorted prefix [1,2,3] and potential suffix connections
3
Optimal Removal
Remove [10,4,2] (length 3) to get sorted array [1,2,3,3,5]
Key Takeaway
🎯 Key Insight: Keep the longest sorted prefix and suffix, remove only the minimal middle section needed
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code