Smallest Subarray to Sort in Every Sliding Window - Problem

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 (sorted in ascending order).

Important: 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 respective window position.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,1,3,2,5], k = 3
Output: [3,2,2]
💡 Note: Window [4,1,3] needs entire array sorted (length 3). Window [1,3,2] needs positions 1,2 sorted (length 2). Window [3,2,5] needs positions 0,1 sorted (length 2).
Example 2 — 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], [3,4,5] are already sorted, so required length is 0 for each.
Example 3 — Single Element Window
$ Input: nums = [5,4,3,2,1], k = 1
Output: [0,0,0,0,0]
💡 Note: All windows have size 1, which are trivially sorted, so required length is 0 for each.

Constraints

  • 1 ≤ k ≤ nums.length ≤ 105
  • -104 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Smallest Subarray to Sort in Every Sliding Window INPUT nums array: 4 i=0 1 i=1 3 i=2 2 i=3 5 i=4 k = 3 (window size) Sliding Windows: [4,1,3] pos 0 [1,3,2] pos 1 [3,2,5] pos 2 nums=[4,1,3,2,5], k=3 ALGORITHM STEPS 1 Find Left Boundary Scan left-to-right for first out-of-order element 2 Find Right Boundary Scan right-to-left for last out-of-order element 3 Calculate Length Length = right - left + 1 (0 if already sorted) 4 Slide Window Repeat for each window position (n-k+1 times) Window Analysis: [4,1,3]: 4>1, need full sort --> 3 [1,3,2]: 3>2, sort [3,2] --> 2 [3,2,5]: 3>2, sort [3,2] --> 2 FINAL RESULT Minimum sort lengths per window: 3 pos 0 2 pos 1 2 pos 2 [3, 2, 2] Window explanations: [4,1,3]: Sort all 3 elements (4>1) [1,3,2]: Sort [3,2] only (3>2) [3,2,5]: Sort [3,2] only (3>2) Key Insight: Two-pass boundary detection finds the minimal unsorted segment: scan left-to-right tracking max seen, then right-to-left tracking min seen. Elements violating sorted order define the boundaries. Time: O((n-k+1) * k) for each window. Space: O(1) extra per window analysis. TutorialsPoint - Smallest Subarray to Sort in Every Sliding Window | Two-Pass Boundary Detection
Asked in
Google 45 Amazon 35 Microsoft 30 Apple 25
23.4K Views
Medium Frequency
~35 min Avg. Time
890 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