Shortest Subarray To Be Removed To Make Array Sorted
Algorithm/TwoPointers
Intuition
The problem asks us to find the shortest subarray that, if removed, allows the remaining elements to be in non-decreasing order. To solve this, we can leverage the sorted segments at the beginning and end of the array and try merging them by removing the middle section.
Approach
Below is the step-by-step breakdown of the approach:
-
Find Left Sorted Segment:
- Traverse from the start to identify the longest initial non-decreasing segment (left pointer).
- If the entire array is sorted, return 0.
-
Find Right Sorted Segment:
- Traverse from the end to identify the longest final non-decreasing segment (right pointer).
-
Calculate Minimum Removal:
- Consider removing either all elements after left or before right.
- Attempt to merge the left and right segments by checking overlapping conditions between the two sorted subarrays.
-
Iterate to Find Overlap:
- Use two pointers (i for left and j for right) to find the minimal overlap that satisfies the sorted condition.
Complexity
- Time complexity: , where is the length of the array, due to a single pass for left and right subarrays and a two-pointer traversal for merging.
- Space complexity: , as the solution uses constant additional space.