Shortest Subarray to be Removed to Make Array Sorted

Medium Topics Company Tags

Remove one contiguous portion of arr, possibly empty, so that the remaining values are non-decreasing. Return the minimum number of entries you must remove. The kept prefix and suffix join together after removal.

Example 1:

Input: arr = [1,5,2,3]

Output: 1

Explanation: Remove the single entry 5. The remaining array [1,2,3] is non-decreasing, and the original array was not sorted.

Example 2:

Input: arr = [3,2,1]

Output: 2

Explanation: The array strictly decreases, so no two entries can remain in non-decreasing order. Remove a length-2 prefix or suffix and keep one entry.

Example 3:

Input: arr = [1,1,1]

Output: 0

Explanation: The equal entries are already in non-decreasing order, so remove an empty subarray.

Constraints:

  • 1 <= arr.length <= 100000
  • 0 <= arr[i] <= 1000000000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.