-
Notifications
You must be signed in to change notification settings - Fork 13
/
solution.py
31 lines (25 loc) · 996 Bytes
/
solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n = len(arr)
# Step 1: Find the longest non-decreasing prefix
left = 0
while left + 1 < n and arr[left] <= arr[left + 1]:
left += 1
# If the entire array is already sorted
if left == n - 1:
return 0
# Step 2: Find the longest non-decreasing suffix
right = n - 1
while right > 0 and arr[right - 1] <= arr[right]:
right -= 1
# Step 3: Find the minimum length to remove by comparing prefix and suffix
result = min(n - left - 1, right)
# Step 4: Use two pointers to find the smallest middle part to remove
i, j = 0, right
while i <= left and j < n:
if arr[i] <= arr[j]:
result = min(result, j - i - 1)
i += 1
else:
j += 1
return result