Shortest Subarray to be Removed to Make Array Sorted Problem
Description
LeetCode Problem 1574.
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.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Constraints:
1 <= arr.length <= 10^50 <= arr[i] <= 10^9
Solution
Approach: Sorted Prefix, Sorted Suffix, Two Pointers
After removing one subarray, what is left is a prefix followed by a suffix. Both must be sorted on their own, and the last kept prefix value must be at most the first kept suffix value.
First find the longest sorted prefix arr[0..i] and the longest sorted suffix arr[j..n-1]. If they overlap (i >= j), the array is already sorted and the answer is 0. Otherwise the removed part must cover arr[i+1..j-1], and there are three kinds of choice:
- keep only a prefix: remove
arr[i+1..], which isn - i - 1values, - keep only a suffix: remove
arr[..j-1], which isjvalues, - keep
arr[0..l]for somel <= iand the suffix starting at somer >= jwitharr[l] <= arr[r], removingr - l - 1values.
For the third case, for each l we want the smallest such r. As l moves right, arr[l] does not decrease, so the smallest valid r does not move left either. A second pointer r that starts at j and only moves forward finds it for every l in one sweep. If r reaches n, we keep no suffix, which is still a valid choice.
Complexity: O(n) time and O(1) extra space.
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n = len(arr)
# arr[0..i] is the longest sorted prefix, arr[j..n-1] the longest sorted suffix
i, j = 0, n - 1
while i + 1 < n and arr[i] <= arr[i + 1]:
i += 1
while j - 1 >= 0 and arr[j - 1] <= arr[j]:
j -= 1
if i >= j:
return 0 # already sorted
best = min(n - i - 1, j) # keep only the prefix, or only the suffix
r = j
for l in range(i + 1):
# keep arr[0..l] and the suffix from the first arr[r] >= arr[l]
while r < n and arr[r] < arr[l]:
r += 1
best = min(best, r - l - 1)
return best