Smallest Subarray to Sort in Every Sliding Window - Problem
You have an integer array and need to analyze sliding windows of size
Think of it like this: you're looking through a magnifying glass of size
If a window is already sorted, the answer is
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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code