# Sliding Window

> The Sliding Window in Algorithms is a technique where a subset of elements in a collection is processed and moved over the collection.

## How does the sliding window technique work?

The technique that moves a fixed or variable-size window across an array or string, updating the result incrementally instead of recomputing it. Ideal for problems involving sums, maximums or substrings within ranges.

- Topic: Various
- Type: technique

## Example

Wrong:

```js
let best = -Infinity;
for (let i = 0; i + k <= nums.length; i++) {
  const sum = nums.slice(i, i + k).reduce((a, b) => a + b, 0);
  best = Math.max(best, sum);
}
```

Right:

```js
let sum = 0, best = -Infinity;
for (let i = 0; i < nums.length; i++) {
  sum += nums[i];
  if (i >= k) sum -= nums[i - k];
  if (i >= k - 1) best = Math.max(best, sum);
}
```

Adding the new element and subtracting the one that left makes each step O(1), so the whole scan is O(n).

## Common mistakes

- Recomputing each window with `slice()` and `reduce()`, turning O(n) into O(n·k).
- Off-by-one window size from using `right - left` instead of `right - left + 1`.

## Key points

- The window updates its running sum or counts as it moves, instead of re-summing every window in O(n·k).
- Character counts inside the window live in a `Map` or fixed-size array, not in repeated `includes()` scans.
- A variable window shrinks from the left in a `while` loop until the constraint holds again.

## Interview questions

### Fixed vs variable sliding window: what is the difference?

A fixed window keeps size k, as in the max sum of k items. A variable window grows and shrinks to meet a condition, as in the longest substring without repeats.

### What is the time complexity of a sliding window?

Usually O(n): each element enters the window once and leaves at most once, even with a nested `while` loop that shrinks it.

### Does a sliding window work with negative numbers?

Fixed-size windows do. A variable window that shrinks when the sum is too large needs non-negative values; with negatives, use prefix sums and a hash map.

## Related cards

- [Two Pointers](https://wonderium.dev/algorithms/two-pointers.md)
- [Array](https://wonderium.dev/algorithms/array.md)
- [String](https://wonderium.dev/algorithms/string.md)
- [O(n)](https://wonderium.dev/algorithms/o-n.md)
- [Map](https://wonderium.dev/js/map.md)

---

- Level: [Algorithms](https://wonderium.dev/algorithms.md)
- HTML version: https://wonderium.dev/algorithms/sliding-window
- Last updated: 2026-11-25
