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
Shortest Subarray Removal to Make Array SortedInput Array:123104235Sorted PrefixRemoveKeepAfter Removal:12335Non-decreasing: 1 ≤ 2 ≤ 3 ≤ 3 ≤ 5 ✓Removed Length: 3Elements removed: [10, 4, 2]Minimum possible removal to make array sorted
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
Asked in
Facebook 35 Amazon 28 Google 22 Microsoft 18
32.4K Views
Medium-High Frequency
~25 min Avg. Time
892 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