DSA
    advanced

    Monotonic Queue (Sliding Window Maximum)

    Monotonic Queue (Sliding Window Maximum)

    Deque-based technique to track max/min in a sliding window in O(n). Essential for Sliding Window Maximum and optimization problems.

    ⏱ O(n)
    💾 O(k)
    Ready
    Input Array (k=3)
    1
    0
    3
    1
    3
    2
    -1
    3
    5
    4
    5
    5
    6
    6
    7
    7
    Monotonic Deque (front=max, back=newest) — decreasing order
    FRONT
    empty
    BACK
    Window Maxima (output)
    —
    —
    —
    —
    —
    —
    —
    —
    front (current max) in deque processing

    Sliding Window Maximum: array=[1,3,3,-1,5,5,6,7], k=3. Deque stores indices in decreasing value order. Front = current window max.

    50%
    Live Variables
    k3
    n8

    Which end does it leave from?

    Sort

    For the sliding-window maximum deque, sort each reason an index is removed.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    Popped from the back

    Drop items here

    Popped from the front

    Drop items here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    In the Sliding Window Maximum problem, how does a Monotonic Queue differ structurally from a Monotonic Stack?

    The short version

    Like VIP bouncers at a club. As new people arrive, anyone less important gets kicked out from the back. The front always has the most important person currently in the window.

    In more depth

    Deque Magic

    Monotonic Queue maintains elements in sorted order within a sliding window.

    For Maximum in Window:

    1.Add new element: Pop from back while back < new element, then push
    2.Get max: Front is always the current maximum
    3.Slide window: If front index is out of window, pop from front

    Key Insight:

    Elements are stored in decreasing order. When the max leaves the window, the next max is already at the front.

    Key Gotchas:

    Store indices, not values, to check window bounds
    Pop from BACK when new element is larger
    Pop from FRONT when index exits window

    When to reach for this

    • Max/Min in every sliding window of size k
    • DP optimization with fixed-range max lookup
    • Subarray problems with window constraints
    • Keywords: 'sliding window', 'maximum/minimum in every window'

    Interview Questions

    Uber
    Bloomberg
    Netflix
    Microsoft
    Uber
    Netflix
    Google
    Amazon
    Bloomberg
    Facebook
    Airbnb
    LinkedIn

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required