Sliding Window Algorithm
Algorithm Optimization
Coding Techniques
Data Structures
Programming Tips

How to implement a better sliding window algorithm?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

A sliding window algorithm becomes "better" when it reuses work from the previous window instead of recomputing everything from scratch. The key is to maintain just enough state as the left and right boundaries move so each element is added and removed only a small number of times.

Recognize When Sliding Window Fits

Sliding window is a good fit when the problem asks about a contiguous range in an array or string. Typical examples include:

  • maximum sum of a length-k subarray
  • longest substring without repeating characters
  • shortest subarray meeting a target condition

If the problem is not about contiguous ranges, sliding window is often the wrong tool.

Fixed-Size Window: Reuse the Previous State

For a fixed-size window, a common beginner mistake is recomputing each window from scratch.

Naive approach:

python
1def max_sum_naive(nums, k):
2    best = float("-inf")
3    for i in range(len(nums) - k + 1):
4        best = max(best, sum(nums[i:i + k]))
5    return best

Better sliding window:

python
1def max_sum_window(nums, k):
2    if k <= 0 or k > len(nums):
3        raise ValueError("invalid window size")
4
5    current_sum = sum(nums[:k])
6    best = current_sum
7
8    for right in range(k, len(nums)):
9        current_sum += nums[right]
10        current_sum -= nums[right - k]
11        best = max(best, current_sum)
12
13    return best
14
15
16print(max_sum_window([2, 1, 5, 1, 3, 2], 3))

The second version is better because it updates the sum in constant time as the window moves.

Variable-Size Window Needs an Invariant

For variable-size windows, the real trick is maintaining an invariant. For example:

  • no duplicate characters in the current substring
  • current sum is below or above a threshold
  • at most k distinct values are inside the window

Classic example:

python
1def longest_unique_substring(s: str) -> int:
2    seen = {}
3    left = 0
4    best = 0
5
6    for right, ch in enumerate(s):
7        if ch in seen and seen[ch] >= left:
8            left = seen[ch] + 1
9        seen[ch] = right
10        best = max(best, right - left + 1)
11
12    return best
13
14
15print(longest_unique_substring("abcabcbb"))

The invariant here is that s[left:right+1] contains no repeated characters.

Shrink the Window Only When Needed

Another strong pattern is to expand the right side until a rule is violated, then shrink from the left until the rule holds again.

python
1def min_subarray_len(target, nums):
2    left = 0
3    current_sum = 0
4    best = float("inf")
5
6    for right, value in enumerate(nums):
7        current_sum += value
8
9        while current_sum >= target:
10            best = min(best, right - left + 1)
11            current_sum -= nums[left]
12            left += 1
13
14    return 0 if best == float("inf") else best
15
16
17print(min_subarray_len(7, [2, 3, 1, 2, 4, 3]))

This works because the input values are positive. With negative numbers, the same pattern can fail because the sum no longer changes monotonically.

Store Only the State You Actually Need

A better sliding window implementation usually comes from keeping the smallest correct amount of state:

  • running sum for numeric windows
  • frequency map for distinct-value problems
  • last-seen positions for substring problems

Too little state forces recomputation. Too much state makes the algorithm hard to follow and easy to break.

Time Complexity Comes From Pointer Movement

People often worry that a nested while loop makes the algorithm quadratic. In many sliding window problems, that is not true because each pointer only moves forward.

If left moves at most n times and right moves at most n times, then the total work is still O(n) even if there is a nested loop on paper.

That is one of the most important mental models for analyzing sliding window performance.

Common Pitfalls

The biggest mistake is recomputing the whole window from scratch instead of updating the state incrementally.

Another common issue is using a variable-size window without a clear invariant. If you cannot state what must always be true inside the window, the code usually becomes guesswork.

People also force sliding window onto problems that involve negative numbers or non-contiguous choices when the technique is not actually appropriate.

Finally, avoid vague variable names. Clear names like left, right, current_sum, and counts make boundary logic much easier to debug.

Summary

  • Sliding window works best for contiguous-range problems with incremental updates.
  • Fixed-size windows usually maintain a running total or count.
  • Variable-size windows depend on a clearly defined invariant.
  • Pointer movement, not loop nesting alone, determines the real complexity.
  • A better sliding window solution is usually simpler: small state, clear rules, and careful boundaries.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.