Sliding Window Problems for Coding Interviews

Sliding window turns many O(n squared) subarray and substring problems into O(n). Keep two pointers that mark a window, grow it on the right, and shrink it from the left while a condition is broken. There are two common shapes: a fixed-size window (maximum sum of k elements) and a variable-size window (longest substring without repeating characters).

To recognise it, look for words like longest, shortest, subarray, substring, contiguous, at most k. Write down what the window must satisfy and what you update when it moves, then code the loop. The problems below are tagged with this pattern and run online.

Coding problems

Related

Frequently asked questions

When should I use a sliding window?

When you need the best contiguous subarray or substring under a condition, and extending or shrinking the range changes the answer in a predictable way.

What is the difference between fixed and variable windows?

A fixed window has a set size and slides one step at a time. A variable window grows until a condition breaks, then shrinks from the left until it holds again.

What is the time complexity?

Usually O(n), because each pointer moves forward at most n times, plus any cost of the structure you keep for the window, such as a hash map.