LeetCode 1574: Shortest Subarray to be Removed to Make Array Sorted Solution
Master LeetCode problem 1574 (Shortest Subarray to be Removed to Make Array Sorted), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1574. Shortest Subarray to be Removed to Make Array Sorted
Problem 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.
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1574 (Shortest Subarray to be Removed to Make Array Sorted)?
This page provides optimized solutions for LeetCode problem 1574 (Shortest Subarray to be Removed to Make Array Sorted) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1574 (Shortest Subarray to be Removed to Make Array Sorted)?
The time complexity for LeetCode 1574 (Shortest Subarray to be Removed to Make Array Sorted) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1574 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1574 in Java, C++, or Python.