A window of fixed width
After this: Slide a window of width k with a running sum: subtract what leaves, add what enters.
On this page · 8 sections · 3 checks
In the last two lessons, each pointer marked one cell to look at. In this lesson the two pointers mark the two ends of a stretch of the array, and every cell between them counts.
Here are six rainfall readings, one per day: [2, 1, 5, 1, 3, 2]. Which three days in a row had the most rain?
The slow way
You could add up every group of three days. Each group is three additions, starting from zero.
| Days (indexes) | Sum |
|---|---|
| 0 to 2 | 2 + 1 + 5 = 8 |
| 1 to 3 | 1 + 5 + 1 = 7 |
| 2 to 4 | 5 + 1 + 3 = 9 |
| 3 to 5 | 1 + 3 + 2 = 6 |
That is 4 groups × 3 additions = 12 additions. But look at the first two groups. They share the cells that hold 1 and 5, and we added those twice.
A picture: the view from a train
Imagine you are on a train, looking out of a window at a row of houses. You can see three houses at a time. When the train moves forward by one house, one house leaves your view on one side, and one new house enters on the other side. The houses in the middle stay in view.
We can treat the array in the same way. A is a stretch of neighbouring cells that moves along the array. When it moves one place, one cell leaves and one cell enters.
Using what you already know
So we do not need to add everything again. We keep the sum of the window, and we change it by two operations: subtract the cell that leaves, and add the cell that enters.
- The first window is 2 + 1 + 5 = 8. That takes three additions.
- Slide once: 2 leaves and 1 enters. 8 − 2 + 1 = 7.
- Slide again: 1 leaves and 3 enters. 7 − 1 + 3 = 9.
- Slide again: 5 leaves and 2 enters. 9 − 5 + 2 = 6.
The sums are 8, 7, 9 and 6, the same as before. The largest is 9, from the window [5, 1, 3].
This took 3 additions for the first window, then 2 operations for each of the 3 slides. That is 9 operations instead of 12. A saving of three is small, but the saving grows quickly with longer arrays and wider windows. A value that you keep updating in this way is called a .
The general rule
We write k for the width of the window. The two pointers are called lo, the left end, and hi, the right end. A window holds every cell from lo to hi, including both ends. So hi − lo + 1 = k. For example, the window from index 1 to index 3 has 3 − 1 + 1 = 3 cells.
How many windows are there? With six cells and a width of 3, a window can start at index 0, 1, 2 or 3. That is four windows, or 6 − 3 + 1. In general there are n − k + 1 windows.
- Adding every window from the start takes k additions for each of the n − k + 1 windows. When the window is small compared with the array, that is close to n × k.
- Sliding takes k additions for the first window, and 2 operations for each slide after it. That is about 2n operations at most, and the width of the window does not make it worse. So sliding costs O(n), which means that the work grows at the same rate as the array.
The code
def window_sums(nums, k): window = sum(nums[:k]) # the first window: k additions sums = [window] for hi in range(k, len(nums)): window += nums[hi] # one enters window -= nums[hi - k] # one leaves sums.append(window) return sums
sums = window_sums([2, 1, 5, 1, 3, 2], 3)print(sums, max(sums))[8, 7, 9, 6] 9
import java.util.*;
public class Main { static List<Integer> windowSums(int[] nums, int k) { int window = 0; for (int i = 0; i < k; i++) window += nums[i]; // the first window: k additions List<Integer> sums = new ArrayList<>(); sums.add(window); for (int hi = k; hi < nums.length; hi++) { window += nums[hi]; // one enters window -= nums[hi - k]; // one leaves sums.add(window); } return sums; }
public static void main(String[] args) { List<Integer> sums = windowSums(new int[] {2, 1, 5, 1, 3, 2}, 3); System.out.println(sums + " " + Collections.max(sums)); }}[8, 7, 9, 6] 9
Here is how to read it.
windowholds the running sum. The first lines add up the first k cells.- The loop moves
hi, the right end of the window, from index k to the end of the array. - The highlighted lines are the slide.
nums[hi]enters.nums[hi - k]leaves, because that cell is now one place too far to the left. For example, when k is 3 andhiis 3, index 0 leaves. - The code adds first and subtracts second. The result is the same in either order.
Watch it happen
Watch the sum change at each slide. The second run uses a window of width 2.
- Window of 3The width is 3. The first sum takes three additions. Each slide after it takes two operations.
- Window of 2
- 02
- 11
- 25
- 31
- 43
- 52
Run an operation to begin.
Check yourself
Over [2, 1, 5, 1, 3, 2], the window slides from indexes 0 to 2 (sum 8) to indexes 1 to 3. Which cells change the sum, and what is the new sum?
window_sumswindowSums is the function from this lesson. What does this print for a width of 2?
sums = window_sums([2, 1, 5, 1, 3, 2], 2)print(sums, max(sums))List<Integer> sums = windowSums(new int[] {2, 1, 5, 1, 3, 2}, 2);System.out.println(sums + " " + Collections.max(sums));There are n = 1,000 readings and a window of width k = 100. About how many additions and subtractions does sliding make, compared with adding up every window from the start?
Connect
- Add up the first window of width k in k additions, then slide it in two operations: subtract what leaves, add what enters.
- Count the windows (n − k + 1) and the total work: about 2n when sliding, and k for each window when adding from the start.
- Say which values can be slid this way (sums, counts) and which cannot (a maximum).