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.
Examples
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.
Solution
Method 1 - Two Pointer Technique
We can follow this approach:
- Identify the longest non-decreasing subarray from the beginning.
- Identify the longest non-decreasing subarray from the end.
- Use a two-pointer technique to find the shortest subarray that can be removed such that the remaining array is non-decreasing by combining parts of the two subarrays from steps 1 and 2.
- The length of the shortest subarray to remove will be the minimum of all possible combinations.
Code
Java
public class Solution {
public int findLengthOfShortestSubarray(int[] arr) {
int n = arr.length;
int left = 0;
// Find the longest non-decreasing subarray from the start
while (left < n - 1 && arr[left] <= arr[left + 1]) {
left++;
}
// If the entire array is non-decreasing
if (left == n - 1) {
return 0;
}
int right = n - 1;
// Find the longest non-decreasing subarray from the end
while (right > 0 && arr[right - 1] <= arr[right]) {
right--;
}
// Compute the minimum length to remove
int ans = Math.min(n - left - 1, right);
int i = 0, j = right;
while (i <= left && j < n) {
if (arr[i] <= arr[j]) {
ans = Math.min(ans, j - i - 1);
i++;
} else {
j++;
}
}
return ans;
}
}
Python
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n = len(arr)
left = 0
# Find the longest non-decreasing subarray from the start
while left < n - 1 and arr[left] <= arr[left + 1]:
left += 1
# If the entire array is non-decreasing
if left == n - 1:
return 0
right = n - 1
# Find the longest non-decreasing subarray from the end
while right > 0 and arr[right - 1] <= arr[right]:
right -= 1
# Compute the minimal length to remove
ans = min(n - left - 1, right)
i, j = 0, right
while i <= left and j < n:
if arr[i] <= arr[j]:
ans = min(ans, j - i - 1)
i += 1
else:
j += 1
return ans
Complexity
- ⏰ Time complexity:
O(n)
, as the solution involves two passes through the array to find the longest non-decreasing subarrays from the start and end, and another pass to combine them. - 🧺 Space complexity:
O(1)