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
Sliding Window: Find Minimum Sort RangeInput: [4,1,3,2,5], k=341325Window 1: [4,1,3]132Window 2: [1,3,2]325Window 3: [3,2,5]Sort Lengths:[4,1,3] → 3[1,3,2] → 2[3,2,5] → 2Output: [3,2,2]
Understanding the Visualization
1
Input
Array [4,1,3,2,5] with sliding windows of size k=3
2
Process
For each window, find minimum range that needs sorting
3
Output
Array of minimum sort lengths [3,2,2]
Key Takeaway
🎯 Key Insight: Compare each window with its sorted version to find minimum disorder range
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