Skip to content

Commit e8b7811

Browse files
authored
Create smallest-subarray-to-sort-in-every-sliding-window.py
1 parent 9d06c06 commit e8b7811

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+
# Time: O(n)
2+
# Space: O(n)
3+
4+
# mono stack, two pointers
5+
class Solution(object):
6+
def minSubarraySort(self, nums, k):
7+
"""
8+
:type nums: List[int]
9+
:type k: int
10+
:rtype: List[int]
11+
"""
12+
def count(nums):
13+
nxt, stk = [n]*n, []
14+
for i in reversed(xrange(n)):
15+
while not (not stk or nums[stk[-1]] >= nums[i]):
16+
stk.pop()
17+
if stk:
18+
nxt[i] = stk[-1]
19+
stk.append(i)
20+
result = []
21+
j, left = 0, -1
22+
for i in xrange(1, n):
23+
if nums[i] < nums[i-1]:
24+
left = i
25+
if i < k-1:
26+
continue
27+
j = max(j, i-(k-1))
28+
while not nxt[j] > left:
29+
j = nxt[j] # or j += 1
30+
result.append(max(i-nxt[j]+1, 0))
31+
return result
32+
33+
n = len(nums)
34+
if k == 1:
35+
return [0]*(n-k+1)
36+
right = count(nums)
37+
for i in xrange((n+1)//2):
38+
nums[i], nums[~i] = -nums[~i], -nums[i]
39+
left = count(nums)
40+
return [max(k-left[~i]-right[i], 0) for i in xrange(n-k+1)]

0 commit comments

Comments
 (0)