← Visualizers
Sliding Window · sub-variant I — monotonic deque windows LeetCode 1438

Longest Continuous Subarray With Absolute Diff ≤ Limit / visualized

The window is valid exactly when max(window) − min(window) ≤ limit. Rescanning the window for its max and min on every step is O(n·k), so you carry the two extremes instead: a decreasing deque whose front is the window max, and an increasing deque whose front is the window min. Each new value back-pops every index it dominates — those indices are younger-and-worse, so they can never be an extreme again while the newcomer is in the window — and each index leaving on the left front-pops only if it happened to be the extreme. Compare LC 239 in this library: sliding window maximum asks for the max, so one deque is enough; 1438 asks about the spread, so it needs both, and the validity test is just maxDeque.front − minDeque.front read every step.

Execution

idle
nums  ·  teal is the window  ·  orange ring = current max  ·  pink ring = current min
maxDequedecreasing
minDequeincreasing
Press Run to begin.
0 / 0
Speed

Java · running line

maxDeque · front = max minDeque · front = min the window longest valid window popped — can never win again
O(n) time · O(n) space  ·  every index is pushed once and popped once across both deques, so the inner while loops are amortised O(1). Sub-variant I: the predicate needs an aggregate the window cannot maintain incrementally, so you maintain the argmax and argmin instead. One deque answers "what is the max" (LC 239); two answer "how wide is the spread".