Back to blog

Sliding Window Technique with Examples

2 March 20262 min read

What Is Sliding Window?

Instead of checking every subarray (O(n²)), maintain a "window" and slide it while updating a running result. Often O(n).

Fixed-Size Window

Window size is given (e.g. K). For each new element, add it; if window size > K, remove from the other end.

Examples

  • Max sum of any subarray of size K.
  • First negative in every window of size K.
  • Maximum in every window of size K (use deque for O(n)).

Variable-Size Window

Window grows and shrinks based on a condition (e.g. "longest subarray with sum ≤ K").

Examples

  • Longest substring with at most K distinct characters.
  • Minimum size subarray with sum ≥ target.
  • Longest substring without repeating characters.

Implementation Tips

  • Use two pointers left and right (or start and end).
  • Use a hash map or variables to track window state.
  • Expand right, then shrink left when the window becomes invalid.

Summary

If the problem asks for a subarray or substring satisfying a condition, think sliding window. Practice on Preplume(/) to build intuition.

Related posts

Common DSA Mistakes and How to Avoid Them

Typical mistakes in coding interviews: off-by-one errors, wrong complexity, and how to avoid them.

14 Mar 20262 min readRead more