Python practice

Python sliding window practice questions

11 problems, ordered from easiest. They run in your browser, and 1 is free.

Start with Best 3-day sales window

The idea in a minute

A sliding window looks at a block of neighbouring items and moves it one step at a time. Instead of recalculating the whole block each step, you add the item that enters and remove the item that leaves.

That turns a slow nested loop into a single pass. The problems begin with a fixed window size and then move to windows that grow and shrink.

Example: Largest sum of 3 in a row

nums = [2, 1, 5, 1, 3, 2]
k = 3
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
    window += nums[i] - nums[i - k]
    best = max(best, window)
print(best)

What it prints

9

What to watch for

  • Update the window total in one step: add the new item, subtract the old one.
  • Be careful with the first window, which needs to be built before the loop starts.
  • For a window that changes size, decide exactly when it is allowed to shrink.

Sliding Window problems

  1. Best 3-day sales windowintermediate · Free
  2. Longest Substring No Repeatintermediate · Locked
  3. Min Window Substringintermediate · Locked
  4. Longest Repeating Char Replaceintermediate · Locked
  5. Permutation in Stringintermediate · Locked
  6. Find All Anagramsintermediate · Locked
  7. Sliding Window Maxintermediate · Locked
  8. Longest Substring K Distinctintermediate · Locked
  9. Find Anagrams Windowintermediate · Locked
  10. Longest streak of active daysintermediate · Locked
  11. Sliding window unique visitor countadvanced · Locked

Want a guided order across every topic? Open the practice sheets or the Python hub.