Sliding Window

Data Structures & Algorithms · Array Techniques · Intermediate · 14 min

Look at a moving 'window' of the data instead of re-checking everything.

A stretchy frame laid over a string. The right edge keeps sliding forward to grab new letters. The moment a letter repeats, the left edge creeps forward until the repeat falls out.

The idea in everyday words

Picture looking through a train window: as the train moves, one new tree appears on the right and one old tree disappears on the left. You don't re-count all trees: just add the new one and remove the old one.

When to use it

Problems about a contiguous chunk: "max sum of k consecutive days", "longest substring without repeats", "smallest subarray with sum ≥ X".

One catch for the sum problems: shrinking from the left only makes the sum smaller when every number is non-negative (0 or more). With negative numbers that is no longer true, so a window can miss the answer. Then use prefix sums instead (and, for the shortest subarray, a monotonic deque).

Fixed window example

Max sum of 3 consecutive numbers in [2, 1, 5, 1, 3, 2]:

  • First window 2+1+5 = 8
  • Slide: drop 2, add 1 → 1+5+1 = 7
  • Slide: drop 1, add 3 → 5+1+3 = 9 ← best
  • Slide: drop 5, add 2 → 1+3+2 = 6

Each slide is 1 subtraction + 1 addition → O(n) instead of O(n·k).

Variable window

Grow the right edge; when the window becomes 'invalid' (e.g. has a repeat), shrink from the left until it's valid again. Track the best size.

Step by step

  1. Start on "abcabcbb":

    left = 0, seen = {}, best = 0. The right edge walks the string one letter at a time.

  2. right = 0, 1, 2:

    a, b, c are all new: add each one. Window "abc", length 3, best = 3.

  3. right = 3: a again:

    a is already inside. Shrink from the left: remove s[0] = a, left = 1. Now add the new a. Window "bca", still 3.

  4. right = 4, 5:

    b repeats → drop b, left = 2, window "cab". c repeats → drop c, left = 3, window "abc". Still 3.

  5. right = 6: b:

    b is inside "abc". One removal (a) is not enough, so keep shrinking: drop a, then b. left = 5, window "cb". That is why it must be a while loop.

  6. Answer:

    right = 7 (b) shrinks to "b". The best ever seen is 3. Each letter entered once and left at most once: O(n).

Code example

def max_sum_k(nums, k):
    window = sum(nums[:k])
    best = window
    for i in range(k, len(nums)):
        window += nums[i] - nums[i - k]
        best = max(best, window)
    return best

print(max_sum_k([2, 1, 5, 1, 3, 2], 3))

Complexity

  • Time: O(n): each item enters the window once and leaves at most once
  • Space: O(1) for a fixed-size sum; O(k) for the set in longest_unique, where k = number of different characters

Interview tips

  • 'Longest substring without repeating characters' is a very common question.

  • Explain why each element enters and leaves the window at most once → O(n).

Challenge: Longest Unique Stretch

Return the length of the longest substring without repeating characters.

Example: longest_unique("abcabcbb") → 3 ("abc")

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Array Techniques

Previous: Fast & Slow Pointers · Next: Prefix Sums