Arrays & Hashing · Pattern 12 of 26
Sliding window of a variable size
Grow the window on the right; when it breaks the rule, shrink it from the left until it is valid again. Both ends only move forward, so it is O(n).
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Longest or shortest subarray / substring that satisfies a condition
- The condition only gets worse as the window grows (more distinct letters, bigger sum with positive numbers)
- Count subarrays where every smaller window is also valid
The template
// longest substring without repeating characters: shrink while invalid
int lengthOfLongestSubstring(String s) {
Map<Character, Integer> count = new HashMap<>();
int best = 0;
for (int l = 0, r = 0; r < s.length(); r++) {
char c = s.charAt(r);
count.merge(c, 1, Integer::sum); // grow on the right
while (count.get(c) > 1) { // invalid: shrink from the left
count.merge(s.charAt(l++), -1, Integer::sum);
}
best = Math.max(best, r - l + 1);
}
return best;
}
// shortest subarray with sum >= target (positive numbers): shrink while valid
int minSubArrayLen(int target, int[] nums) {
int best = Integer.MAX_VALUE, sum = 0;
for (int l = 0, r = 0; r < nums.length; r++) {
sum += nums[r];
while (sum >= target) { best = Math.min(best, r - l + 1); sum -= nums[l++]; }
}
return best == Integer.MAX_VALUE ? 0 : best;
} def length_of_longest_substring(s): # shrink while invalid
count, best, l = {}, 0, 0
for r, c in enumerate(s):
count[c] = count.get(c, 0) + 1 # grow on the right
while count[c] > 1: # invalid: shrink from the left
count[s[l]] -= 1
l += 1
best = max(best, r - l + 1)
return best
def min_sub_array_len(target, nums): # shortest with sum >= target: shrink while valid
best, total, l = float('inf'), 0, 0
for r, x in enumerate(nums):
total += x
while total >= target:
best = min(best, r - l + 1)
total -= nums[l]
l += 1
return 0 if best == float('inf') else best // longest substring without repeating characters: shrink while invalid
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> count;
int best = 0;
for (int l = 0, r = 0; r < (int)s.size(); r++) {
count[s[r]]++; // grow on the right
while (count[s[r]] > 1) count[s[l++]]--; // invalid: shrink from the left
best = max(best, r - l + 1);
}
return best;
}
// shortest subarray with sum >= target (positive numbers): shrink while valid
int minSubArrayLen(int target, vector<int>& nums) {
int best = INT_MAX, sum = 0;
for (int l = 0, r = 0; r < (int)nums.size(); r++) {
sum += nums[r];
while (sum >= target) { best = min(best, r - l + 1); sum -= nums[l++]; }
}
return best == INT_MAX ? 0 : best;
} // longest substring without repeating characters: shrink while invalid
function lengthOfLongestSubstring(s) {
const count = new Map();
let best = 0;
for (let l = 0, r = 0; r < s.length; r++) {
count.set(s[r], (count.get(s[r]) ?? 0) + 1); // grow on the right
while (count.get(s[r]) > 1) { // invalid: shrink from the left
count.set(s[l], count.get(s[l]) - 1); l++;
}
best = Math.max(best, r - l + 1);
}
return best;
}
// shortest subarray with sum >= target (positive numbers): shrink while valid
function minSubArrayLen(target, nums) {
let best = Infinity, sum = 0;
for (let l = 0, r = 0; r < nums.length; r++) {
sum += nums[r];
while (sum >= target) { best = Math.min(best, r - l + 1); sum -= nums[l++]; }
}
return best === Infinity ? 0 : best;
} The variations
-
1Longest window that stays valid
Grow, then shrink only until valid again, then record the length. For "at most k replacements", the window is valid while length − most frequent count ≤ k.
Now you solve- Longest Repeating Character Replacement Medium Stuck? solution
- Max Consecutive Ones III Medium Stuck? solution
- Fruit Into Baskets Medium Stuck? solution
- Maximum Length Substring With Two Occurrences Easy Stuck? solution
- Max Consecutive Ones Easy Stuck? solution
- Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit Medium Stuck? solution
- Maximum Number of Visible Points Hard Stuck? solution
-
2Shortest window that becomes valid
Grow until valid, then shrink while it stays valid, recording the length at every step.
-
3Count the windows
If every sub-window of a valid window is valid, each right end adds
r − l + 1subarrays. For exact conditions, use atMost(k) − atMost(k − 1) or track the last bad index.Now you solve -
4More practice
More problems that use this pattern. Try them once the variations above feel easy.
Mistakes to avoid
- Using a sliding window when numbers can be negative: shrinking no longer makes the sum smaller. Use prefix sums.
- Recording the answer inside the shrink loop for "longest" (it belongs after) or outside it for "shortest" (it belongs inside).
- Counting subarrays: add
r − l + 1for every r, the number of valid windows ending at r.
Lesson done
Next: Sliding window with a hash map →Mark it done once you can write the template from memory and you have solved the worked examples yourself.