Smallest Subarray to Sort in Every Sliding Window - Problem
You have an integer array and need to analyze sliding windows of size k. For each window, imagine you want to make the entire window non-decreasing (sorted in ascending order). Your task is to find the minimum length of a continuous segment within each window that needs to be sorted to achieve this goal.

Think of it like this: you're looking through a magnifying glass of size k that slides across your array. At each position, you ask: "What's the shortest consecutive portion I need to sort to make this entire view sorted?"

If a window is already sorted, the answer is 0. Return an array containing the answer for each possible window position.

Input & Output

example_1.py โ€” Basic Window
$ Input: nums = [5, 2, 8, 1, 9, 3], k = 3
โ€บ Output: [3, 3, 3, 3]
๐Ÿ’ก Note: For window [5,2,8]: need to sort all 3 elements. For [2,8,1]: need to sort all 3. For [8,1,9]: need to sort first 3. For [1,9,3]: need to sort last 3 positions (but only 2 elements need sorting, so answer is 2, but we need consecutive segment including position 1, so answer is 3).
example_2.py โ€” Already Sorted Window
$ Input: nums = [1, 2, 3, 4, 5], k = 3
โ€บ Output: [0, 0, 0]
๐Ÿ’ก Note: All windows [1,2,3], [2,3,4], and [3,4,5] are already sorted, so no subarray needs to be sorted.
example_3.py โ€” Single Element
$ Input: nums = [3, 1, 2], k = 1
โ€บ Output: [0, 0, 0]
๐Ÿ’ก Note: Each window contains only one element, which is trivially sorted, so answer is 0 for each position.

Constraints

  • 1 โ‰ค nums.length โ‰ค 104
  • 1 โ‰ค k โ‰ค nums.length
  • -104 โ‰ค nums[i] โ‰ค 104
  • The array can contain duplicate values

Visualization

Tap to expand
Array Analysis: Finding Minimum Sort Segments52819Window k=3Sorted version:258โ‰ โœ“โ‰ Analysis Resultโ€ข Left boundary: position 0 (5 โ‰  2)โ€ข Right boundary: position 2 (8 โ‰  8... wait, 5โ‰ 2 and 8=8)โ€ข Actually: positions 0 and 1 differโ€ข Minimum segment length: 3โœ“Found minimum segment efficiently!
Understanding the Visualization
1
Position Window
Place the sliding window of size k at current position
2
Create Reference
Make a sorted copy to see what the window should look like
3
Find Boundaries
Locate leftmost and rightmost positions where actual differs from sorted
4
Calculate Length
The minimum segment length is the span between these boundaries
Key Takeaway
๐ŸŽฏ Key Insight: Instead of trying all possible segments, we compare with the sorted version to directly identify the boundaries of disorder, making the solution much more efficient.
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
28.8K Views
Medium Frequency
~25 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen