File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments