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 [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
Shortest Subarray Removal StrategyInput Array123104235Sorted Prefix[1, 2, 3]Sorted Suffix[3, 5]Remove This[10, 4, 2]Strategy ComparisonOption 1Keep prefix onlyRemove: 5 elementsResult: [1, 2, 3]Length: 5Option 2Keep suffix onlyRemove: 6 elementsResult: [3, 5]Length: 6Option 3 โœ“Connect prefix + suffixRemove: 3 elementsResult: [1, 2, 3, 3, 5]Length: 3Final Answer: 3Minimum subarray removal length to make array sorted
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.
Asked in
Facebook 35 Google 28 Amazon 22 Microsoft 18
42.0K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen