Sliding Window Basics
How a window that slides along an array answers questions about runs of neighbouring numbers in one pass.
Picture a paper frame laid over a row of numbers, showing only a few of them at a time. You slide it along the row, and at every stop you only need to look at what came in and what went out. A sliding window does exactly that in code. It answers questions about neighbouring items of an array or string, such as the largest sum of three numbers in a row.
Runs of neighbouring numbers
All the examples use the same six numbers, nums = [2, 3, 1, 2, 4, 3]
Four questions about runs come up again and again. Here they are for those six numbers:
- Which run of exactly 3 numbers has the largest sum?
- What is the shortest run with a sum of at least 7?
- What is the longest run with a sum of at most 7?
- How many runs have a sum of at least 7?
A window is the run you are looking at right now. Two indexes describe it: leftrightleft = 1right = 3right - left + 1
Checking every run
Why not simply try every run? Two loops do it, one inside the other. The outer loop picks the first index, and the inner loop moves the last index forward one step at a time, adding each new number to a sum. For our six numbers that makes 21 runs, and finding the shortest run with a sum of at least 7 this way means checking all 21. For n numbers there are n(n + 1)/2 runs, so doubling the array roughly quadruples the work.
Most of that work is repeated: the runs 3, 1, 2 and 1, 2, 4 share the 1 and the 2, yet each adds them up again. A sliding window keeps the sum of the current window and changes it only by the numbers that enter or leave. Each number enters the window once and leaves it at most once, so a single pass over the array is enough.
Fixed-size windows
Which 3 numbers in a row have the largest sum? Every candidate has the same length, so the window keeps a fixed size, called kk = 3
The row labelled window 1 holds 2, 3, 1, with sum 6. To reach window 2, the 2 at index 3 enters on the right and the 2 at index 0 leaves on the left. The new sum is 6 + 2 - 2 = 6, found with one addition and one subtraction instead of three additions.
The same step gives window 3 (6 + 4 - 3 = 7) and window 4 (7 + 3 - 1 = 9). Window 4, drawn in orange, holds 2, 4, 3 and has the largest sum, 9.
In code, one loop moves the window's right edge along the array, with the index rightnums[right]rightknums[right - k]kright = k - 1
Variable-size windows: the shortest run
What is the shortest run with a sum of at least 7? Now the length is the answer, so the window has to stretch and shrink. While the sum is too small, rightleft
Follow the rows of the picture from the top. The window 2, 3, 1 has sum 6, marked "too small: grow", so it takes in the 2 at index 3. The sum is now 8, so length 4 is recorded and the 2 at index 0 leaves. The window 3, 1, 2 is too small again and grows to take in the 4.
The blue rows are too small and grow. The teal rows are valid, and each is recorded before it shrinks. The orange row, 4, 3 with sum 7, is the shortest of them, with length 2. After it, the window is down to the last 3, with sum 3 and no numbers left to take in.
Why is it safe to drop the 2 at index 0 for good? Length 4 has already been recorded for the window that starts there. Any later window starting at index 0 would be longer than 4, so none of them can be the shortest. The same reasoning holds at every step, so left
Variable-size windows: the longest run
What about the longest run with a sum of at most 7? The steps are the same as for the shortest run, in a different order. First grow by one number. If the sum is now above 7, the window is broken, so drop numbers from the left until the sum is at most 7 again. Only then is the window valid, so its length is recorded after the shrinking, not during it.
On our six numbers, the window grows to 2, 3, 1 with sum 6. Adding the 2 at index 3 makes 8, so the first 2 leaves and the window is 3, 1, 2. Adding the 4 makes 10, so the 3 leaves and the window is 1, 2, 4, with sum exactly 7. Adding the last 3 makes 10 again, and this time two numbers, 1 and 2, leave before the window 4, 3 is valid. Three windows reached length 3, and none was longer, so the answer is 3.
So the shortest-run and longest-run windows differ in where the length is recorded. For the shortest run, the window is valid while it shrinks. For the longest run, it is valid only once the shrinking has finished.
Counting runs with a window
How many runs have a sum of at least 7? A window can count them in groups, using the shrinking rule from the shortest run: after taking in nums[right]leftrightleft - 1left
The picture is taken when right = 4left = 3
So leftrightleftright
The templates in Java
The program below has one method per question, plus the slow way for comparison:
- Fixed size:
, which rejects amaxSumOfK below 1 or longer than the array.k - Shortest run:
, which records inside the shrinking loop and returns 0 when no run reaches the target.shortestWithSumAtLeast - Longest run:
, which records after the shrinking loop.longestWithSumAtMost - Counting:
, which addscountWithSumAtLeast after the shrinking loop.left - Slow way:
, which returns the shortest length and how many runs it checked.bruteShortest
The main[2, 3, 1, 2, 4, 3]longint
public class SlidingWindowBasics {
// Fixed size: the largest sum of any k elements in a row.
static long maxSumOfK(int[] nums, int k) {
if (k <= 0 || k > nums.length) {
throw new IllegalArgumentException("k must be between 1 and " + nums.length);
}
long sum = 0;
long best = Long.MIN_VALUE;
for (int right = 0; right < nums.length; right++) {
sum += nums[right]; // nums[right] enters the window
if (right >= k) {
sum -= nums[right - k]; // nums[right - k] leaves it
}
if (right >= k - 1) {
best = Math.max(best, sum); // the window holds exactly k elements
}
}
return best;
}
// Variable size, shortest: length of the shortest run with sum >= target, 0 if none.
static int shortestWithSumAtLeast(int[] nums, int target) {
int left = 0;
long sum = 0;
int best = Integer.MAX_VALUE;
for (int right = 0; right < nums.length; right++) {
sum += nums[right]; // grow
while (sum >= target) { // valid: record, then try a shorter one
best = Math.min(best, right - left + 1);
sum -= nums[left];
left++;
}
}
return best == Integer.MAX_VALUE ? 0 : best;
}
// Variable size, longest: length of the longest run with sum <= limit.
static int longestWithSumAtMost(int[] nums, int limit) {
int left = 0;
long sum = 0;
int best = 0;
for (int right = 0; right < nums.length; right++) {
sum += nums[right]; // grow
while (sum > limit) { // broken: shrink until valid again
sum -= nums[left];
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
}
// Counting: how many runs have sum >= target.
static long countWithSumAtLeast(int[] nums, int target) {
int left = 0;
long sum = 0;
long count = 0;
for (int right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum >= target) {
sum -= nums[left];
left++;
}
count += left; // starts 0 .. left - 1 all work
}
return count;
}
// The slow way: try every start and every end.
static int[] bruteShortest(int[] nums, int target) {
int best = Integer.MAX_VALUE;
int checked = 0;
for (int start = 0; start < nums.length; start++) {
long sum = 0;
for (int end = start; end < nums.length; end++) {
sum += nums[end];
checked++;
if (sum >= target) {
best = Math.min(best, end - start + 1);
}
}
}
return new int[] {best == Integer.MAX_VALUE ? 0 : best, checked};
}
public static void main(String[] args) {
int[] nums = {2, 3, 1, 2, 4, 3};
System.out.println("Largest sum of 3 in a row: " + maxSumOfK(nums, 3));
System.out.println("Shortest with sum >= 7: " + shortestWithSumAtLeast(nums, 7));
System.out.println("Longest with sum <= 7: " + longestWithSumAtMost(nums, 7));
System.out.println("Runs with sum >= 7: " + countWithSumAtLeast(nums, 7));
int[] slow = bruteShortest(nums, 7);
System.out.println("Slow way: shortest " + slow[0] + ", runs checked " + slow[1]);
System.out.println("Shortest with sum >= 100: " + shortestWithSumAtLeast(nums, 100));
System.out.println("Longest with sum <= 0: " + longestWithSumAtMost(nums, 0));
System.out.println("Largest sum of 6 in a row: " + maxSumOfK(nums, 6));
try {
maxSumOfK(nums, 7);
} catch (IllegalArgumentException e) {
System.out.println("Largest sum of 7 in a row: " + e.getMessage());
}
int[] big = {2000000000, 1000000000, 500000000};
System.out.println("Largest sum of 2 in a row, big values: " + maxSumOfK(big, 2));
int[] withNegative = {1, -1, 5};
System.out.println("With a negative number, window says: "
+ shortestWithSumAtLeast(withNegative, 5));
System.out.println("With a negative number, slow way says: "
+ bruteShortest(withNegative, 5)[0]);
}
}
Running it prints:
Largest sum of 3 in a row: 9
Shortest with sum >= 7: 2
Longest with sum <= 7: 3
Runs with sum >= 7: 9
Slow way: shortest 2, runs checked 21
Shortest with sum >= 100: 0
Longest with sum <= 0: 0
Largest sum of 6 in a row: 15
Largest sum of 7 in a row: k must be between 1 and 6
Largest sum of 2 in a row, big values: 3000000000
With a negative number, window says: 3
With a negative number, slow way says: 1
The first four lines answer the four questions with 9, 2, 3 and 9 runs, the same numbers the windows gave when followed by hand. The fifth line shows the slow way agreeing on length 2, after checking all 21 runs.
The line Shortest with sum >= 100: 0
Where a window goes wrong
A sliding window is only right when its condition has a direction: adding a number always pushes the sum one way, and removing it always pushes it back. The last three output lines come from two inputs that trip a window up.
Negative numbers
In [1, -1, 5]
With a negative number in the array, a shorter window can have a larger sum, so stopping the shrinking early is no longer safe. Such problems need a different tool, for example running totals from index 0 (prefix sums) kept in a map, as in
Sums too large for an int
In [2000000000, 1000000000, 500000000]k = 2intintint
Spotting a sliding window problem
How do you tell that a new problem fits a window? Three signs together point to one:
- The question is about runs: words such as subarray, substring, "in a row" or "consecutive".
- It asks for the largest, smallest, shortest or longest such run, or how many there are.
- The condition has a direction: adding an item pushes it one way, and removing the item pushes it back. Sums of positive numbers work, and so do the number of different letters in a piece of text, the number of zeros in a run, and letter counts compared with a target.
When the third sign is missing, a twist sometimes brings it back: run the window several times, each time fixing one extra value such as how many different letters the window may hold. The window's leftright
Complexity
Each template makes one pass, and the slow way does not.
- Time: O(n) for every template, because
visits each of the n numbers once andright only moves forward, at most n steps in all.left - Time of the slow way: O(n2), because its two loops check all n(n + 1)/2 runs, 21 of them for our six numbers.
- Space: O(1) for the templates here, because they keep only
,left , the sum and the answer.right
A window that must remember which letters or values it holds needs a map, a set or a deque for them, and that takes space for the items inside the window.
Where to go next
Fixed-size windows:
Maximum Average Subarray I is the fixed-size largest sum, turned into an average.Permutation in String slides a window of letters and compares its letter counts with a target.Sliding Window Maximum keeps the largest value of each window, not its sum, with a deque.
Variable-size windows, shortest run:
Minimum Size Subarray Sum is the shortest run with a sum of at least a target.Minimum Window Substring finds the shortest piece of text that contains all the letters of another string.
Variable-size windows, longest run:
Longest Substring Without Repeating Characters moves past the earlier copy whenever a letter repeats.leftMax Consecutive Ones III counts the zeros inside the window instead of summing.Longest Repeating Character Replacement keeps letter counts to decide when the window is broken.
Counting and twists:
Number of Substrings Containing All Three Characters counts runs by adding , as in the counting example.leftLongest Substring with At Least K Repeating Characters shows why a plain window fails there and how running it once for each possible number of different letters fixes that; its main solution splits the text instead.