Skip to content
Lesson 4 of 10 · Coding Interview Prep: Data Structures and Algorithms

Sliding window

Slide a window over a list, adding on one side and removing on the other, to answer subarray questions in O(n).

22 min

A subarray is a run of neighboring items. Questions like "the best 7-day stretch" or "the shortest run that adds up to at least 20" tempt you into a double loop: for every start, scan forward. That is O(n²). A sliding window reuses the work: when the window moves one step, you add the new item and drop the old one, instead of recomputing the whole sum.

The best sum of k consecutive items:

python5 lines
window = sum(a[:k])            # first window
best = window
for i in range(k, len(a)):
    window += a[i] - a[i - k]  # add the entering item, drop the leaving one
    best = max(best, window)

Each item enters once and leaves once: O(n).

Keep two indexes, left and right. Grow by moving right; shrink by moving left while the window is valid (or invalid). For "shortest run with sum at least target" in a list of positive numbers:

python9 lines
left = total = 0
best = 0
for right, x in enumerate(a):
    total += x
    while total >= target:
        length = right - left + 1
        best = length if best == 0 else min(best, length)
        total -= a[left]
        left += 1

left never moves backwards, so although there is a while inside the for, the total number of steps is at most 2n: still O(n).

The window must have a monotonic property: adding an item moves the sum or count in one direction. With positive numbers, a bigger window means a bigger sum, so shrinking is safe. With negative numbers this breaks, and you need a different tool (prefix sums and a dict).

The same idea gives "longest substring without repeating characters": grow the window, and when a character repeats, move left past its previous position. A dict of last positions keeps it O(n).

How it got here
  1. Step 1

    Start empty

    left = 0, right = 0, total = 0, best = none yet.

  2. Step 2

    Grow

    Move right: add a[right] to the total.

  3. Step 3

    Check

    Is the window good (total at least target)?

  4. Step 4

    Record and shrink

    While good: record its length, subtract a[left], move left.

  5. Step 5

    Repeat

    Keep growing until right reaches the end.

Exercise7 checks
python

A river sensor logs positive rainfall amounts, one per day. Write shortest_window(nums, target): the length of the shortest run of consecutive days whose total is at least target. Return 0 if no run reaches it. All numbers are positive. O(n).

shortest_window([2, 3, 1, 2, 4, 3], 7) is 2 (the run 4 and 3).

Your code must satisfy

  • shortest_window([2, 3, 1, 2, 4, 3], 7)→2example
  • shortest_window([1, 1, 1], 3)→3whole list needed
  • shortest_window([1, 1, 1], 10)→0impossible
  • shortest_window([1, 9, 1], 5)→1single big day
  • shortest_window([], 4)→0empty
  • shortest_window([5, 1, 3, 5, 10, 7, 4, 9, 2, 8], 15)→2exact
starter code2 lines
def shortest_window(nums, target):
    pass
Exercise7 checks
python

Write best_week(sales, k): the largest total of any k consecutive days. If k is 0 or bigger than the list, return 0. Use a fixed window, not a nested loop.

best_week([4, 2, 9, 1, 3], 2) is 11 (the days 2 and 9).

Your code must satisfy

  • best_week([4, 2, 9, 1, 3], 2)→11example
  • best_week([1, 2, 3], 3)→6k equals length
  • best_week([1, 2], 5)→0k too big
  • best_week([1, 2], 0)→0k zero
  • best_week([], 1)→0empty
  • best_week([5, 9, 2], 1)→9k one
starter code2 lines
def best_week(sales, k):
    pass
Common misconception

“A `while` loop inside a `for` loop always means O(n²).”

Nested loops usually do mean that.

What is actually true

It depends on whether the inner loop restarts. Here left only moves forward and never resets, so across the whole run it moves at most n times. Total work is at most 2n steps: O(n).

How to catch yourself

Count how many times each *index* can move in total, not how deep the loops are nested.

Checklist
0/4

Is it a sliding window problem?

  • A sliding window updates a running answer as one item enters and one leaves, instead of recomputing: O(n).
  • Fixed windows add a[i] and subtract a[i - k].
  • Variable windows grow with right and shrink with left while a condition holds; left never goes backwards.
  • Needs a monotonic measure, such as sums of positive numbers.
Check yourself

Window checks.

1Multiple choice

What is the time complexity of the variable-size window in this lesson?

  • AO(n²)
  • BO(n)
  • CO(log n)
  • DO(n log n)
2Numeric answer

What is the largest sum of 2 consecutive items in [1, 5, 2, 8, 3]?

3Multiple choice

Which breaks the shrink-while-big-enough logic?

  • APositive numbers
  • BNegative numbers in the array
  • CA fixed window
  • DAn empty list
4Multiple choice

In a fixed window of size k, when index i enters, which index leaves?

  • A`i + k`
  • B`i - k`
  • C`i - 1`
  • D`0`
5Fill the blanks

A run of neighboring items in a list is called a .

Capitalisation, spacing and punctuation are ignored when grading.

Practise this lesson, not just read it

In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Coding Interview Prep: Data Structures and Algorithms is planned around your week. Free.