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 to Remove INPUT arr = [1,2,3,10,4,2,3,5] 1 0 2 1 3 2 10 3 4 4 2 5 3 6 5 7 Keep Remove Two Pointers Setup: Left ptr: Find sorted prefix [1,2,3] sorted left=2 Right ptr: Find sorted suffix [3,5] sorted right=6 left right ALGORITHM STEPS 1 Find Left Boundary Scan from start while sorted left = 2 (at value 3) 2 Find Right Boundary Scan from end while sorted right = 6 (at value 3) 3 Try Merge Points Connect prefix with suffix arr[left] <= arr[right]? 4 Calculate Min Remove Track minimum length min(n-left-1, right, ...) Best Merge Found: 1 2 3 X X X 3 5 Remove indices 3,4,5 (length 3) FINAL RESULT Remaining Sorted Array: 1 2 3 3 5 1 <= 2 <= 3 <= 3 <= 5 [OK] OUTPUT 3 Removed subarray: [10, 4, 2] From index 3 to 5 Length = 5 - 3 + 1 = 3 Time: O(n) | Space: O(1) Single pass with two pointers Key Insight: The optimal solution connects the longest sorted prefix with the longest sorted suffix. Use two pointers to find where arr[left] <= arr[right], minimizing the removed middle portion. Try all valid merge points: remove only suffix, remove only prefix, or merge prefix+suffix. TutorialsPoint - Shortest Subarray to be Removed to Make Array Sorted | Optimized Two Pointers - Linear Time
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