Shortest Subarray to be Removed to Make Array Sorted

medium array two pointers binary search stack monotonic stack

Problem

Given arr, remove a contiguous subarray (possibly empty) so the rest is non-decreasing. Return the minimum length to remove.

Inputarr = [1,2,3,10,4,2,3,5]
Output3
Remove [10,4,2] to leave [1,2,3,3,5].

def find_length_of_shortest_subarray(arr):
    n = len(arr); L = 0
    while L + 1 < n and arr[L] <= arr[L + 1]: L += 1
    if L == n - 1: return 0
    R = n - 1
    while R > 0 and arr[R - 1] <= arr[R]: R -= 1
    ans = min(n - L - 1, R)
    i, j = 0, R
    while i <= L and j < n:
        if arr[i] <= arr[j]:
            ans = min(ans, j - i - 1); i += 1
        else:
            j += 1
    return ans
function findLengthOfShortestSubarray(arr) {
  const n = arr.length;
  let L = 0;
  while (L + 1 < n && arr[L] <= arr[L + 1]) L++;
  if (L === n - 1) return 0;
  let R = n - 1;
  while (R > 0 && arr[R - 1] <= arr[R]) R--;
  let ans = Math.min(n - L - 1, R);
  let i = 0, j = R;
  while (i <= L && j < n) {
    if (arr[i] <= arr[j]) { ans = Math.min(ans, j - i - 1); i++; }
    else j++;
  }
  return ans;
}
class Solution {
    public int findLengthOfShortestSubarray(int[] arr) {
        int n = arr.length, L = 0;
        while (L + 1 < n && arr[L] <= arr[L + 1]) L++;
        if (L == n - 1) return 0;
        int R = n - 1;
        while (R > 0 && arr[R - 1] <= arr[R]) R--;
        int ans = Math.min(n - L - 1, R);
        int i = 0, j = R;
        while (i <= L && j < n) {
            if (arr[i] <= arr[j]) { ans = Math.min(ans, j - i - 1); i++; }
            else j++;
        }
        return ans;
    }
}
int findLengthOfShortestSubarray(vector& arr) {
    int n = arr.size(), L = 0;
    while (L + 1 < n && arr[L] <= arr[L + 1]) L++;
    if (L == n - 1) return 0;
    int R = n - 1;
    while (R > 0 && arr[R - 1] <= arr[R]) R--;
    int ans = min(n - L - 1, R);
    int i = 0, j = R;
    while (i <= L && j < n) {
        if (arr[i] <= arr[j]) { ans = min(ans, j - i - 1); i++; }
        else j++;
    }
    return ans;
}
Time: O(n) Space: O(1)