# LeetCode 239: Sliding Window Maximum — Step-by-Step Visual Trace

**Hard** — Sliding Window | Deque | Queue | Array

## The Problem

Find the maximum element in each sliding window of size k as it moves from left to right through an array. Return an array containing the maximum value for each window position.

## Approach

Use a deque to maintain indices of array elements in decreasing order of their values. For each element, remove smaller elements from the back, add current index, remove indices outside the current window from front, and collect maximums when window is full.

**Time:** O(n) · **Space:** O(k)

## Code

```python
from collections import deque

class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        if not nums or k <= 0:
            return []

        result = []
        window = deque()

        for i, num in enumerate(nums):
            while window and nums[window[-1]] < num:
                window.pop()

            window.append(i)

            if i - window[0] >= k:
                window.popleft()

            if i >= k - 1:
                result.append(nums[window[0]])

        return result
```

## Watch It Run

> **[Open interactive visualization](https://tracelit.dev/app?trace=0239_sliding-window-maximum)**

> **Try it yourself:** Open [TraceLit](https://tracelit.dev/app?trace=0239_sliding-window-maximum) and step through every line.

---

*Built with [TraceLit](https://tracelit.dev) — the visual algorithm tracer for LeetCode practice.*
