A window that grows and shrinks
After this: Grow a window until it reaches the target, then shrink it while it still does.
On this page · 9 sections · 4 checks
In the last lesson, the window always had the same width. Sometimes you do not know the width in advance.
Here is an example. The array is [2, 3, 1, 2, 4, 3], and the target is 7. What is the shortest stretch of neighbouring cells whose sum is at least 7?
A window of fixed width cannot answer this, because the width is the thing we are looking for. So we let the width change. Think of the window as a rubber band laid over part of the array. The right end can stretch it, and the left end can pull it shorter.
Grow, then shrink
As before, lo is the left end of the window and hi is the right end. Each round has two parts.
- Grow. Move
hione cell to the right, and add that cell to the sum. - Shrink. While the sum still reaches the target, record the window's length if it is the shortest so far. Then subtract the cell at
loand moveloone cell to the right.
Then go back to step 1, until hi has passed the end of the array.
The smallest example
Take [1, 1, 4] with a target of 4.
- Grow to
[1]. The sum is 1, which is below 4. - Grow to
[1, 1]. The sum is 2, which is below 4. - Grow to
[1, 1, 4]. The sum is 6, which reaches 4. Record length 3. Drop the first 1, and the sum is 5. - The window is
[1, 4]. The sum is 5, which reaches 4. Record length 2. Drop the 1, and the sum is 4. - The window is
[4]. The sum is 4, which reaches 4. Record length 1. Drop the 4, and the sum is 0. - The sum is below 4 and
hiis at the end, so we stop.
The shortest window has length 1: the single cell that holds 4.
The larger example
Now the same steps on [2, 3, 1, 2, 4, 3] with a target of 7. Each row is one round of grow and shrink.
hi | Cell added | Sum | What happens | Shortest so far |
|---|---|---|---|---|
| 0 | 2 | 2 | Below 7, so keep growing. | none |
| 1 | 3 | 5 | Below 7, so keep growing. | none |
| 2 | 1 | 6 | Below 7, so keep growing. | none |
| 3 | 2 | 8 | Length 4 works. Drop 2: the sum is 6, so stop shrinking. | 4 |
| 4 | 4 | 10 | Length 4 works, but it is no shorter. Drop 3: the sum is 7, and length 3 works. Drop 1: the sum is 6, so stop shrinking. | 3 |
| 5 | 3 | 9 | Length 3 works, but it is no shorter. Drop 2: the sum is 7, and length 2 works. Drop 4: the sum is 3, so stop shrinking. | 2 |
The shortest window is [4, 3], with length 2.
For a target of 16, no window ever works, because the whole array adds up to only 15. The function then returns 0, which means that it found no window.
Why lo never goes back
Look at the row where hi is 3. The window covers indexes 0 to 3, and we record length 4. Then we drop index 0 for good. Can we lose anything by doing that?
Think about every other window that starts at index 0.
- A window that ends earlier does not reach 7. We know this because
hikept growing past those points. - A window that ends later is longer than 4, so it cannot beat the length we have recorded.
So no window that starts at index 0 can do better. lo can move on and never come back.
Why this is O(n)
This code has a loop inside a loop, and in Trying every pair a loop inside a loop was O(n²). The difference is that the inner loop here does not start again each time. It carries on from where it stopped.
So count the moves of the pointers. hi moves n times. lo only moves right, and it can move at most n times in the whole pass, because there are only n cells to drop. That makes at most 2n moves. The cost is O(n), which means that the work grows at the same rate as the array.
The code
def min_window(nums, target): lo, window, best = 0, 0, 0 # best 0 means: no window found yet for hi in range(len(nums)): window += nums[hi] # grow: hi joins the window while window >= target: # it works: shrink while it still does length = hi - lo + 1 if best == 0 or length < best: best = length window -= nums[lo] # lo leaves the window lo += 1 return best
print(min_window([2, 3, 1, 2, 4, 3], 7))print(min_window([2, 3, 1, 2, 4, 3], 16))2 0
public class Main { static int minWindow(int[] nums, int target) { int lo = 0, window = 0, best = 0; // best 0 means: no window found yet for (int hi = 0; hi < nums.length; hi++) { window += nums[hi]; // grow: hi joins the window while (window >= target) { // it works: shrink while it still does int length = hi - lo + 1; if (best == 0 || length < best) best = length; window -= nums[lo]; // lo leaves the window lo++; } } return best; }
public static void main(String[] args) { System.out.println(minWindow(new int[] {2, 3, 1, 2, 4, 3}, 7)); System.out.println(minWindow(new int[] {2, 3, 1, 2, 4, 3}, 16)); }}2 0
Here is how to read it.
windowis the running sum, andbestis the shortest length so far. Abestof 0 means that no window has worked yet.- The outer loop is the grow step. It moves
hiand adds the new cell. - The inner
whileloop is the shrink step. It runs as long as the sum still reaches the target, and it may run many times or not at all. hi - lo + 1is the number of cells in the window.
Watch it happen
- Smallest window with sum ≥ 7The target is 7. Watch hi grow the window until the sum reaches 7. Then watch lo shrink it while the sum still reaches 7.
- Smallest window with sum ≥ 16
- 02
- 13
- 21
- 32
- 44
- 53
Run an operation to begin.
Check yourself
What does this print?
def min_window(nums, target): lo, window, best = 0, 0, 0 # best 0 means: no window found yet for hi in range(len(nums)): window += nums[hi] # grow: hi joins the window while window >= target: # it works: shrink while it still does length = hi - lo + 1 if best == 0 or length < best: best = length window -= nums[lo] # lo leaves the window lo += 1 return best
print(min_window([2, 3, 1, 2, 4, 3], 7))print(min_window([2, 3, 1, 2, 4, 3], 16))public class Main { static int minWindow(int[] nums, int target) { int lo = 0, window = 0, best = 0; // best 0 means: no window found yet for (int hi = 0; hi < nums.length; hi++) { window += nums[hi]; // grow: hi joins the window while (window >= target) { // it works: shrink while it still does int length = hi - lo + 1; if (best == 0 || length < best) best = length; window -= nums[lo]; // lo leaves the window lo++; } } return best; }
public static void main(String[] args) { System.out.println(minWindow(new int[] {2, 3, 1, 2, 4, 3}, 7)); System.out.println(minWindow(new int[] {2, 3, 1, 2, 4, 3}, 16)); }}The window at indexes 0 to 3 of [2, 3, 1, 2, 4, 3] adds up to 8, which reaches 7. Why shrink it from the left before growing again, rather than recording length 4 and moving on?
Target 7, same array. When hi reaches index 4 (value 4) and the shrinking stops, where is lo, what is the window's sum, and what is best?
There is a while loop inside the for loop. Why is the pass still O(n)?
Connect
- Grow a window from the right until it reaches the target, then shrink it from the left while it still does.
- Explain why lo never moves back, and why the two pointers make at most 2n moves.
- Say that grow-and-shrink needs values that are not negative.