JavaScript Snippet

Sliding Window Template

Difficulty: Easy

Sliding window is the linear-time alternative to nested loops for substring-and-subarray problems. This snippet covers the fixed-size window for max-sum-of-k, the variable-size window for longest-substring-with-condition, and the at-most-K shrinkable form that handles 'at most / exactly K distinct' problems with one trick.

Code Snippets
/

Sliding Window Template

Sliding Window Template

Sliding window is the linear-time alternative to nested loops for substring-and-subarray problems. This snippet covers the fixed-size window for max-sum-of-k, the variable-size window for longest-substring-with-condition, and the at-most-K shrinkable form that handles 'at most / exactly K distinct' problems with one trick.

JavaScript
Easy
3 snippets
algorithms
sliding-window
code-template
two-pointers

994 views

12

When the window size is fixed, the trick is to compute the first window's sum once and then slide it by adding the new element and removing the old one (sum += arr[i] - arr[i - k]). This O(n) update replaces the O(n*k) recomputation a naive solution would do. The same skeleton handles fixed-size averages, max-of-k, and any aggregate that supports incremental update. The early-return when the array is shorter than k is the easy edge case to forget.