
Before diving into the pattern, let me give you a quick intro. I'm a Information Science student and a competitive programmer. Over time, as I practiced problems in contests and interviews, I began to see patterns—especially in problems dealing with sequences. One of the most effective and commonly used patterns is Sliding Window.
Sliding Window is a technique typically used for problems involving subarrays or substrings. It allows you to avoid unnecessary repeated computations by maintaining a window over a portion of the data and sliding it forward as needed, keeping track of required information dynamically.
Let’s walk through the pattern and highlight key points along with some classic problems.
Problem Statement
Given an array or string, find the maximum/minimum/number of something in a subarray/substring of fixed or variable length.
Approach
Maintain a window of size k (fixed) or use two pointers to create a dynamic-sized window.
Slide the window by adding the new element and removing the old one while updating the result accordingly.
Use auxiliary data structures like a queue or hash map when needed (e.g., for character count, frequency).
Java Template (Fixed-Length Window)
public int maxSum(int[] nums, int k) {
int maxSum = 0, windowSum = 0;
for (int i = 0; i < nums.length; i++) {
windowSum += nums[i];
if (i >= k) {
windowSum -= nums[i - k];
}
if (i >= k - 1) {
maxSum = Math.max(maxSum, windowSum);
}
}
return maxSum;
}
Java Template (Variable-Length Window)
public int minSubArrayLen(int target, int[] nums) {
int left = 0, sum = 0, minLen = Integer.MAX_VALUE;
for (int right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum >= target) {
minLen = Math.min(minLen, right - left + 1);
sum -= nums[left++];
}
}
return minLen == Integer.MAX_VALUE ? 0 : minLen;
}
Similar Problems
| Problem | Difficulty | Link |
|---|---|---|
| 209. Minimum Size Subarray Sum | Medium | 🔗 |
| 3. Longest Substring Without Repeating Characters | Medium | 🔗 |
| 1004. Max Consecutive Ones III | Medium | 🔗 |
| 76. Minimum Window Substring | Hard | 🔗 |
| 438. Find All Anagrams in a String | Medium | 🔗 |
| 424. Longest Repeating Character Replacement | Medium | 🔗 |
| 567. Permutation in String | Medium | 🔗 |
| 2958. Length of Longest Subarray With at Most K Frequency | Medium | 🔗 |
| 239. Sliding Window Maximum | Hard | 🔗 |
| 30. Substring with Concatenation of All Words | Hard | 🔗 |