Skip to content

Commit c159cad

Browse files
authored
Create shortest-subarray-to-be-removed-to-make-array-sorted.py
1 parent b647399 commit c159cad

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def findLengthOfShortestSubarray(self, arr):
6+
"""
7+
:type arr: List[int]
8+
:rtype: int
9+
"""
10+
j = -1
11+
for j in reversed(xrange(1, len(arr))):
12+
if arr[j-1] > arr[j]:
13+
break
14+
else:
15+
return 0
16+
result = j
17+
for i in xrange(j):
18+
if i and arr[i] < arr[i-1]:
19+
break
20+
while j < len(arr) and arr[i] > arr[j]:
21+
j += 1
22+
result = min(result, (j-i+1)-2)
23+
return result
24+
25+
26+
# Time: O(n)
27+
# Space: O(1)
28+
class Solution2(object):
29+
def findLengthOfShortestSubarray(self, arr):
30+
"""
31+
:type arr: List[int]
32+
:rtype: int
33+
"""
34+
result = 0
35+
for i in xrange(1, len(arr)):
36+
if arr[i-1] <= arr[i]:
37+
continue
38+
j = len(arr)-1
39+
while j > i and (j == len(arr)-1 or arr[j] <= arr[j+1]) and arr[i-1] <= arr[j]:
40+
j -= 1
41+
result = j-i+1
42+
break
43+
for j in reversed(xrange(len(arr)-1)):
44+
if arr[j] <= arr[j+1]:
45+
continue
46+
i = 0
47+
while i < j and (i == 0 or arr[i-1] <= arr[i]) and arr[i] <= arr[j+1]:
48+
i += 1
49+
result = min(result, j-i+1)
50+
break
51+
return result

0 commit comments

Comments
 (0)