1574. Shortest Subarray to be Removed to Make Array Sorted #834
-
Topics: Given an integer array Return the length of the shortest subarray to remove. A subarray is a contiguous subsequence of the array. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use sorting and binary search techniques. Here’s the plan: Approach:
Let's implement this solution in PHP: 1574. Shortest Subarray to be Removed to Make Array Sorted <?php
/**
* @param Integer[] $arr
* @return Integer
*/
function shortestSubarrayToRemove($arr) {
$n = count($arr);
// Find the longest non-decreasing prefix
$left = 0;
while ($left < $n - 1 && $arr[$left] <= $arr[$left + 1]) {
$left++;
}
// If the entire array is sorted
if ($left == $n - 1) {
return 0;
}
// Find the longest non-decreasing suffix
$right = $n - 1;
while ($right > 0 && $arr[$right - 1] <= $arr[$right]) {
$right--;
}
// Minimum removal when keeping only the prefix or suffix
$minRemove = min($n - $left - 1, $right);
// Try to merge prefix and suffix
$i = 0;
$j = $right;
while ($i <= $left && $j < $n) {
if ($arr[$i] <= $arr[$j]) {
$minRemove = min($minRemove, $j - $i - 1);
$i++;
} else {
$j++;
}
}
return $minRemove;
}
// Test cases
echo shortestSubarrayToRemove([1, 2, 3, 10, 4, 2, 3, 5]) . "\n"; // Output: 3
echo shortestSubarrayToRemove([5, 4, 3, 2, 1]) . "\n"; // Output: 4
echo shortestSubarrayToRemove([1, 2, 3]) . "\n"; // Output: 0
?> Explanation:
Complexity
This solution efficiently finds the shortest subarray to be removed to make the array sorted by using a two-pointer technique, and it handles large arrays up to the constraint of |
Beta Was this translation helpful? Give feedback.
We can use sorting and binary search techniques. Here’s the plan:
Approach:
Two Pointers Approach:
left
pointer).right
pointer).Monotonic Stack:
Steps:
left
).right
).