Monotonic Deque Tracks Sliding Window Maximum
A deque of indices kept value-decreasing answers each sliding-window maximum in amortized constant time because every index enters and leaves the queue once.
Code
from collections import deque
def window_max(values, k):
# Queue holds indices whose values stay decreasing: head is the window max
dq = deque()
result = []
for i, v in enumerate(values):
# Pop smaller tails first - they can never be a future maximum
while dq and values[dq[-1]] <= v:
dq.pop()
dq.append(i)
# Drop the head once it slides out of the window
if dq[0] <= i - k:
dq.popleft()
# Report the head once the first full window exists
if i >= k - 1:
result.append(values[dq[0]])
return result
latencies = [12, 45, 8, 30, 60, 22, 90, 15]
print("latencies:", latencies)
print("window=3 max:", window_max(latencies, 3))
print("window=1 max:", window_max(latencies, 1))Output
Captured from a sandboxed run of this snippet in the build pipeline.
latencies: [12, 45, 8, 30, 60, 22, 90, 15]
window=3 max: [45, 45, 60, 60, 90, 90]
window=1 max: [12, 45, 8, 30, 60, 22, 90, 15]What the demo tracks
window_max keeps a deque of indices whose values stay decreasing, so the head is always the current window maximum. For the latencies list with window 3 it prints 45, 45, 60, 60, 90, 90.
Each new value pops smaller tails first, since they can never win a future window, then appends itself; a head that slid out of range is dropped once. Every index enters and leaves once, which is the amortized O(1) behind the result list.
Caveats and details
- Values are read through the stored indices, never copied into the deque.
- window=1 degenerates to reporting every element.
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Why store indices instead of values?
- Expiry needs positions: the head is dropped when dq[0] <= i - k, so indices serve both the value lookup and the window boundary in one entry.
Report a problem with this exampleOpens a pre-filled issue on GitHub.