# Sliding Window — Data Structures & Algorithms

Source: https://www.geekswithgeeks.com/en/dsa/sliding-window

> Maintain a running window over a sequence, expanding and shrinking it in one pass.

## Expand right, shrink left

For "longest/shortest/best contiguous subarray or substring" problems: move `right` to include a new element; while the window breaks a constraint, move `left` to drop elements. Each index enters and leaves once — `O(n)`.

## Longest substring without repeats

Track the last index of each character; jump `left` past any repeat.

```python
def longest_unique(s):
    last = {}
    left = best = 0
    for right, c in enumerate(s):
        if c in last and last[c] >= left:
            left = last[c] + 1
        last[c] = right
        best = max(best, right - left + 1)
    return best
```

Output:

```
longest_unique("abcabcbb") -> 3   ("abc")
```

## Spotting it

Keywords: "contiguous", "subarray/substring", "at most K", "sum equals", "longest/shortest". Fixed-size window is even simpler — slide by one and adjust the running total.
