1574. Shortest Subarray to be Removed to Make Array Sorted
Difficulty: Medium
Topics: Array, Two Pointers, Binary Search, Stack, Monotonic Stack
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:
Example 2:
Example 3:
Constraints:
Hint:
Solution:
We can use sorting and binary search techniques. Here’s the plan:
Two Pointers Approach:
Monotonic Stack:
Steps:
Optimization:
Let's implement this solution in PHP: 1574. Shortest Subarray to be Removed to Make Array Sorted
Explanation:
Longest Non-Decreasing Prefix and Suffix:
- The prefix is determined by traversing the array from the start until elements are in non-decreasing order.
- Similarly, the suffix is determined by traversing from the end.
Initial Minimum Removal:
- Calculate the removal length by keeping only the prefix or the suffix.
Merging Prefix and Suffix:
- Use two pointers (i for prefix and j for suffix) to find the smallest subarray to remove such that the last element of the prefix is less than or equal to the first element of the suffix.
Return Result:
- The result is the minimum length of the subarray to remove, calculated as the smaller of the initial removal or the merging of prefix and suffix.
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 10^5 elements.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Shortest Subarray to be Removed to Make Array Sorted. For more information, please follow other related articles on the PHP Chinese website!