Shortest Subarray to be Removed to Make Array Sorted - Problem
Imagine you have an array of integers that's almost sorted, but has some elements out of place. Your goal is to remove the shortest possible contiguous subarray to make the remaining elements completely non-decreasing.
For example, given
Key Points:
For example, given
[1, 2, 3, 10, 4, 2, 3, 5], you could remove the subarray [10, 4, 2] to get [1, 2, 3, 3, 5], which is non-decreasing.Key Points:
- A subarray is a contiguous sequence of elements
- You can remove an empty subarray (length 0) if the array is already sorted
- The remaining elements must be in non-decreasing order (duplicates allowed)
- Find the minimum length subarray to remove
Input & Output
example_1.py โ Basic Case
$
Input:
[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. This is the shortest possible removal.
example_2.py โ Already Sorted
$
Input:
[1, 2, 3, 4, 5]
โบ
Output:
0
๐ก Note:
Array is already non-decreasing, so no removal needed. Return 0.
example_3.py โ Remove Entire Middle
$
Input:
[5, 4, 3, 2, 1]
โบ
Output:
4
๐ก Note:
Keep only one element (any single element is sorted). Remove 4 elements to achieve this.
Constraints
- 1 โค arr.length โค 105
- 0 โค arr[i] โค 109
- The array contains at least 1 element
- Elements can be equal (non-decreasing allows duplicates)
Visualization
Tap to expand
Understanding the Visualization
1
Identify Sorted Prefix
Find the longest non-decreasing sequence from the start
2
Identify Sorted Suffix
Find the longest non-decreasing sequence from the end
3
Evaluate Options
Consider three removal strategies and pick the best
4
Apply Two Pointers
Use two pointers to find optimal connection between prefix and suffix
Key Takeaway
๐ฏ Key Insight: The optimal solution leverages the fact that we want to preserve as much of the already-sorted portions as possible. By identifying the longest sorted prefix and suffix, we can minimize the middle section that needs to be removed.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code