LeetCode 1574: Shortest Subarray to be Removed to Make Array Sorted
LeetCode 1574 Solution Explanation
Explanation
To solve this problem, we need to find the minimum number of elements that need to be removed from the given array arr
to make the remaining elements non-decreasing. We can achieve this by identifying the longest non-decreasing prefix and suffix of the array and then determining the minimum length of the subarray to be removed.
- Find the length of the longest non-decreasing prefix starting from the beginning of the array.
- Find the length of the longest non-decreasing suffix starting from the end of the array.
- If the entire array is non-decreasing, return 0.
- Otherwise, we need to find the minimum subarray to be removed. This can be done by removing the middle part between the prefix and suffix.
The time complexity of this approach is O(n), where n is the number of elements in the array. The space complexity is O(1) as we are using only a constant amount of extra space.
LeetCode 1574 Solutions in Java, C++, Python
class Solution {
public int findLengthOfShortestSubarray(int[] arr) {
int n = arr.length;
int left = 0, right = n - 1;
// Find the length of the longest non-decreasing prefix
while (left + 1 < n && arr[left] <= arr[left + 1]) {
left++;
}
// If the entire array is non-decreasing
if (left == n - 1) {
return 0;
}
// Find the length of the longest non-decreasing suffix
while (right > 0 && arr[right - 1] <= arr[right]) {
right--;
}
int res = Math.min(n - left - 1, right);
int i = 0, j = right;
while (i <= left && j < n) {
if (arr[i] <= arr[j]) {
res = Math.min(res, j - i - 1);
i++;
} else {
j++;
}
}
return res;
}
}
Interactive Code Editor for LeetCode 1574
Improve Your LeetCode 1574 Solution
Use the editor below to refine the provided solution for LeetCode 1574. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...