Sliding Window
23 / 170Sliding WindowLesson 2 of 6About 65 min
The standard loop, and why a nested while inside a for is still linear.
The mechanics above are fixed. What changes between problems is the state: what the window remembers, and what makes it illegal. For the problem below, decide those two things first, then drop them into this loop.
Run the loop above on [2, 1, 5, 1, 3, 2] with a limit of 8. After each expansion and any shrinking, give the window total, left, and the window size. The first three steps are done for you to check against; fill in the rest.
| right | total | left | size |
|---|---|---|---|
| 3 | |||
| 4 | |||
| 5 |
Three variations on the same loop. max_sum_of_k returns the largest sum of any k consecutive values using a rolling total, not a fresh sum per window. longest_at_most_two_distinct returns the length of the longest stretch containing at most two distinct characters. count_windows_summing_to counts how many stretches of non-negative values sum to exactly the target.
Tests
print(max_sum_of_k([2, 1, 5, 1, 3, 2], 3), max_sum_of_k([1, 2], 5))print(longest_at_most_two_distinct("eceba"), longest_at_most_two_distinct("aaaa"))print(count_windows_summing_to([1, 2, 3], 3), count_windows_summing_to([0, 0, 3], 3))Output
Run tests to see output.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.