Lesson 2 · Unit 02
Grow and shrink
Let the window stretch on the right and tighten on the left
What you practise
- Smallest subarray with sum ≥ target
- Why the inner while is still O(n)
Try a question from this lesson
Pick one
All numbers are positive. A run of neighbours sums to 15, and you need at least 11. How do you look for a SHORTER run that still reaches 11?
Correct answer
Drop items from the left while the sum stays ≥ 11
Why
With positive numbers, dropping an item always lowers the sum, so you can peel items off the left for as long as the sum stays high enough. Starting again would re-add everything you already summed.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Grow, then shrink
The right edge moves one item per step: the window grows. Whenever the window is good enough, pull the left edge in as far as it will go, recording each size on the way.
This finds the shortest run of positive numbers with a sum of at least target (or 0 if there is none).
def min_window(nums, target):
n = len(nums)
left, total, best = 0, 0, n + 1
for r in range(n):
total += nums[r]
while total >= target:
best = min(best, r - left + 1)
total -= nums[left]
left += 1
return 0 if best > n else bestfunction minWindow(nums, target) {
const n = nums.length;
let left = 0, total = 0, best = n + 1;
for (let r = 0; r < n; r++) {
total += nums[r];
while (total >= target) {
best = Math.min(best, r - left + 1);
total -= nums[left];
left += 1;
}
}
return best > n ? 0 : best;
}function minWindow(
nums: number[],
target: number,
): number {
const n = nums.length;
let left = 0, total = 0, best = n + 1;
for (let r = 0; r < n; r++) {
total += nums[r];
while (total >= target) {
best = Math.min(best, r - left + 1);
total -= nums[left];
left += 1;
}
}
return best > n ? 0 : best;
}Python note0 if best > n else best is a conditional expression: the value before if when the test is true, the value after else otherwise.
TypeScript notebest > n ? 0 : best is the ternary operator, the same idea as Python's 0 if best > n else best with the test written first.
10 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 2× fill the blanks
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.