Smallest Subarray to Sort in Every Sliding Window Problem
#3555
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3555.
You are given an integer array nums and an integer k.
For each contiguous subarray of length k, determine the minimum length of a continuous segment that must be sorted so that the entire window becomes non‑decreasing; if the window is already sorted, its required length is zero.
Return an array of length n − k + 1 where each element corresponds to the answer for its window.
Example 1:
Input: nums = [1,3,2,4,5], k = 3
Output: [2,2,0]
Explanation:
- nums[0...2] = [1, 3, 2]. Sort [3, 2] to get [1, 2, 3], the answer is 2.
- nums[1...3] = [3, 2, 4]. Sort [3, 2] to get [2, 3, 4], the answer is 2.
- nums[2...4] = [2, 4, 5] is already sorted, so the answer is 0.
Example 2:
Input: nums = [5,4,3,2,1], k = 4
Output: [4,4]
Explanation:
- nums[0...3] = [5, 4, 3, 2]. The whole subarray must be sorted, so the answer is 4.
- nums[1...4] = [4, 3, 2, 1]. The whole subarray must be sorted, so the answer is 4.
Constraints:
1 <= nums.length <= 10001 <= k <= nums.length1 <= nums[i] <= 10^6
Solution
Approach: Brute Force per Window
Handle each window of length k on its own. The segment to sort is delimited by the right-most element that is out of place and the left-most one.
- Scan the window from left to right, tracking the maximum so far. An element smaller than that maximum has something bigger before it, so it is out of place: record its position as the right end
r. - Scan from right to left, tracking the minimum so far. An element larger than that minimum is out of place: record its position as the left end
l. - If no element was out of place the window is already sorted and the answer is
0; otherwise it isr - l + 1.
Both scans can run in one loop over the window.
Complexity: O(n * k) time and O(1) extra space besides the answer.
from math import inf
class Solution:
def minSubarraySort(self, nums: List[int], k: int) -> List[int]:
def f(i: int, j: int) -> int:
mi, mx = inf, -inf
l = r = -1
for k in range(i, j + 1):
if mx > nums[k]:
r = k
else:
mx = nums[k]
p = j - k + i
if mi < nums[p]:
l = p
else:
mi = nums[p]
return 0 if r == -1 else r - l + 1
n = len(nums)
return [f(i, i + k - 1) for i in range(n - k + 1)]