Skip to content

Commit c4f7b1d

Browse files
committed
1574. Shortest Subarray to be Removed to Make Array Sorted
1 parent c72f538 commit c4f7b1d

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Solution by Sergey Leschev
2+
// 1574. Shortest Subarray to be Removed to Make Array Sorted
3+
4+
// Time: O(N)
5+
// Space: O(1)
6+
7+
function findLengthOfShortestSubarray(arr: number[]): number {
8+
const n = arr.length
9+
let left = 0
10+
let right = n - 1
11+
12+
// Find the longest non-decreasing prefix
13+
while (left + 1 < n && arr[left] <= arr[left + 1]) {
14+
left++
15+
}
16+
// If the entire array is non-decreasing, no need to remove anything
17+
if (left === n - 1) return 0
18+
19+
// Find the longest non-decreasing suffix
20+
while (right > left && arr[right - 1] <= arr[right]) {
21+
right--
22+
}
23+
24+
// Initialize the minimum length to remove as either removing the suffix or prefix
25+
let minRemoveLength = Math.min(n - left - 1, right)
26+
27+
// Try to merge the prefix and suffix
28+
let i = 0
29+
let j = right
30+
while (i <= left && j < n) {
31+
if (arr[i] <= arr[j]) {
32+
minRemoveLength = Math.min(minRemoveLength, j - i - 1)
33+
i++
34+
} else {
35+
j++
36+
}
37+
}
38+
39+
return minRemoveLength
40+
}

0 commit comments

Comments
 (0)