#1574

Shortest Subarray to be Removed to Make Array Sorted

Medium
ArrayTwo PointersBinary SearchStackMonotonic StackTwo PointersSliding WindowArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the idea of finding the longest non-decreasing prefix and suffix. By identifying these two segments, we can determine the shortest subarray to remove by ensuring the end of the prefix is less than the start of the suffix.

⚙️

Algorithm

3 steps
  1. 1Step 1: Identify the longest non-decreasing prefix from the start of the array.
  2. 2Step 2: Identify the longest non-decreasing suffix from the end of the array.
  3. 3Step 3: Use two pointers to find the minimum length of the subarray to remove by checking the conditions between the prefix and suffix.
solution.py17 lines
1def find_length_of_shortest_subarray(arr):
2    n = len(arr)
3    left = 0
4    while left < n - 1 and arr[left] <= arr[left + 1]:
5        left += 1
6    if left == n - 1:
7        return 0
8    right = n - 1
9    while right > 0 and arr[right - 1] <= arr[right]:
10        right -= 1
11    min_length = min(n - left - 1, right)
12    for i in range(left + 1):
13        while right < n and arr[i] > arr[right]:
14            right += 1
15        min_length = min(min_length, right - i - 1)
16    return min_length
17

Complexity note: The time complexity is O(n) because we only traverse the array a few times. The space complexity is O(1) since we only use a few variables to keep track of indices.

  • 1Identifying the longest non-decreasing prefix and suffix is crucial for optimizing the solution.
  • 2Using two pointers allows us to efficiently find the minimum subarray to remove.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.