Learn how the sliding window pattern tracks contiguous ranges in arrays and strings while avoiding repeated work and quadratic nested loops.
The sliding window pattern keeps track of a continuous part of an array or string. The window moves across the input as one unit while we update only the values that enter or leave it.
A window can be represented by two indexes, a running total, a substring, or another small data structure. It usually moves from left to right:
Sliding windows are useful when a problem asks about a contiguous range: consecutive array values, neighboring characters, or a substring.
Core idea
When a window moves by one position, do not calculate the whole window again. Remove the value leaving the window and add the value entering it.
Look for a sliding window when:
k consecutive values.”The two indexes are pointers to the edges of a contiguous interval. The values can be unsorted. For a variable-size window you also need a condition that tells you which edge can move safely.
Write a function called maxSubarraySum that accepts an array of integers and an integer window size k. Return the largest sum of exactly k consecutive values. If k is less than one or exceeds the array length, return null in JavaScript or None in Python.
maxSubarraySum([2, 6, 9, 2, 1, 8, 5, 6, 3], 3) → 19 ([8,5,6])
maxSubarraySum([4, 2, 1, 6], 4) → 13 (array length === 4)
maxSubarraySum([], 3) → nullThe direct solution adds up each window from scratch. The first window's sum becomes the best sum so far. Each later window replaces it only if its sum is larger.
function maxSubarraySumNaive(numbers, size) {
if (size < 1 || size > numbers.length) return null;
let maximum = null;
for (let start = 0; start <= numbers.length - size; start++) {
let current = 0;
for (let offset = 0; offset < size; offset++) {
current += numbers[start + offset];
}
// A null maximum means this is the first window. Save its sum even if it is negative.
if (maximum === null || current > maximum) {
maximum = current;
}
}
return maximum;
}If the array has length n and the requested window has size k, this repeats up to k additions for each starting position. There are exactly n − k + 1 windows, each summed with k additions. A fixed k gives linear time. The total can grow quadratically when k is around half of n.
Start by adding the first size values. For [2, 6, 9, 2, 1, 8, 5, 6, 3] and a window size of 3, the first window is:
[2, 6, 9] → 17To move the window one position, subtract the value leaving on the left and add the value entering on the right:
[2, 6, 9] → [6, 9, 2]
17 - 2 + 2 = 17
[6, 9, 2] → [9, 2, 1]
17 - 6 + 1 = 12The old values are not added again. Each slide performs only one subtraction and one addition.
function maxSubarraySum(numbers, size) {
if (size < 1 || size > numbers.length) return null;
let windowSum = 0;
for (let i = 0; i < size; i++) {
windowSum += numbers[i];
}
let maximum = windowSum;
for (let end = size; end < numbers.length; end++) {
const start = end - size;
windowSum += numbers[end] - numbers[start];
maximum = Math.max(maximum, windowSum);
}
return maximum;
}The first loop creates the initial window. The second loop slides it across the remaining values. Every array item is added once and removed at most once, so the total time is O(n) and the extra space is O(1).
maximum starts at the first real window sum instead of 0. This matters when all values are negative: the answer should remain negative rather than incorrectly becoming zero.
Not every window has a fixed size. Sometimes the window grows until it violates a condition, then shrinks from the left until it becomes valid again.
How long is the longest substring of "abcabcbb" with no repeated character? Step through the scan. The highlighted cells are the characters currently in the set. When the character at R is already in the set, L moves until the earlier copy leaves.
function longestUniqueSubstring(text) {
const window = new Set();
let left = 0;
let longest = 0;
for (let right = 0; right < text.length; right++) {
while (window.has(text[right])) {
window.delete(text[left]);
left++;
}
window.add(text[right]);
longest = Math.max(longest, right - left + 1);
}
return longest;
}Enter up to 64 printable ASCII characters. Spaces count. An empty string is valid.
Step 1 of 15. Add “a” to the window.
Apply the same indexed window in the longest-substring practice.
The right pointer expands the window. When it would add a duplicate, the left pointer removes characters until the window is valid again. Although the code contains a for loop and a while loop, each character enters and leaves the window at most once, so the total time is O(n) with average constant-time set operations.
| Window type | How it moves | Typical problem |
|---|---|---|
| Fixed size | Add one value and remove one value on every slide | Maximum sum of k consecutive values |
| Variable size | Expand and shrink until a condition is satisfied | Longest substring without repeated characters |
| Variable size with a sum threshold | Record a qualifying length, then shrink while the sum still qualifies | Shortest range reaching a target in a positive-valued array |
For shortest-sum windows, positivity makes shrinking predictable: removing the first number always lowers the sum. With negative values, [1, -1, 5] at target 5 shows the problem. A window might record length three, drop the first 1, and stop shrinking at sum four, missing the final [5].
The window should represent exactly the part of the input that is currently being evaluated. Keeping that invariant clear makes it easier to decide what to add, what to remove, and when to update the answer.
| Approach | Main method | Typical time | Extra space |
|---|---|---|---|
| Recalculate each range | Sum or inspect every item for every new window | O(k × (n − k + 1)) for fixed-width sums | O(1) |
| Sliding window | Reuse the previous range and update its edges | O(n) | O(1) or O(k) |
For a variable-size window, a set or map may be needed to track the current contents, so space can grow with the window size.
Pattern checklist
Ask three questions: Is the target data contiguous? What information describes the current window? When the window moves, which value leaves and which value enters? If you can update the answer from those edge changes, a sliding window is likely a good fit.