Skip to content

Commit a609354

Browse files
author
Joseph Luce
authored
Create 581_shortest_unsorted_continuous_subarray.md
1 parent 4f76040 commit a609354

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# 581. Shortest Unsorted Continuous Subarray
2+
3+
## Best solution
4+
- Runtime: O(N)
5+
- Space: O(1)
6+
- N = Number of elements in array
7+
8+
The idea is quite simple. Start from left to right, find the first unsorted index, then from right to left, find the last unsorted index.
9+
From then, you have three subarrays, the left sub-array, the middle sub-array, and the right sub-array.
10+
The middle sub-array is obviously your known set of unsorted numbers but you do not know if your middle sub-array can be further extended to the left or the right.
11+
For example, [1,2,3,4,1,2,1,2,3], the first pass through will only identify index 3 and index 6 as the middle sub-array.
12+
However, you need a second pass through to identify index 1 to index 8 by checking if the numbers of the left or right sub-arrays are in the middle sub-array.
13+
14+
```
15+
class Solution:
16+
def findUnsortedSubarray(self, nums: List[int]) -> int:
17+
first = last = None
18+
for index, n in enumerate(nums[:-1]):
19+
if n > nums[index+1]:
20+
first = index
21+
last = index+1
22+
break
23+
for index, n in reversed(list(enumerate(nums))):
24+
if index > 0 and n < nums[index-1]:
25+
last = index
26+
break
27+
if first is not None:
28+
MIN, MAX = min(nums[first:last+1]), max(nums[first:last+1])
29+
# check outer sub-arrays for similar numbers
30+
for index, n in enumerate(nums[:first]):
31+
if n in range(MIN+1, MAX+1):
32+
first = index
33+
break
34+
for index, n in reversed(list(enumerate(nums))):
35+
if index <= last: # don't iterate into known unsorted array
36+
break
37+
if n in range(MIN, MAX):
38+
last = index
39+
break
40+
return last-first+1
41+
return 0
42+
```

0 commit comments

Comments
 (0)