Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Stacks, Queues & Deques

Monotonic Deque

O(n)

Keep a deque of candidate indices in decreasing value; pop the front when it leaves the window.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
Learn firstMonotonic StackSliding WindowUnlocksConvex Hull Trick / Li Chao Tree
0%
mastery
0/9 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

Max/min of every window of size k; dp[i] = best of dp[j] for j in [i-k, i-1]; shortest subarray with sum >= K with negatives.

  1. 1Brute force

    Scan each window: O(nk); or a heap O(n log n).

  2. 2The observation

    Per-window scanning: dominated elements never become the window extreme.

  3. 3Why it works

    Deque indices increase and their values stay monotone; dominated items leave from the back, expired ones from the front.

Reach for it when

  • +Max or min of every window of size k (or every window length), updated as it slides.
  • +A DP where each state takes the best of the previous k states — Jump Game VI, Constrained Subsequence Sum.
  • +You feel an O(n·k) 'rescan the window for its extreme' that should be O(n).

Not when

  • ×Next greater/smaller with unbounded lookback, no fixed windowuse Monotonic stack
  • ×The window aggregate is a sum, not an extremeuse Prefix sum or a running sum
  • ×Arbitrary range extremes on a static arrayuse Sparse table
  • ×Arbitrary range extremes with updatesuse Segment tree
  • ×Window ends don't both move forward monotonicallyuse Mo's algorithm or segment tree
  • ×You need the k-th order statistic in the windowuse Two heaps or ordered set
  • ×You think a max-heap works: on [8,1,1,1,1], k=2 the expired 8 stays on topuse Deque (heap needs lazy deletion, O(n log n))

Intuition

A deque ("deck") is a queue open at both ends — you can push/pop at the front and the back. A monotonic deque keeps its contents sorted, and it's the tool for "max/min of every sliding window of size k". A monotonic stack answers "next greater"; a monotonic deque answers "current extreme over a moving window" — because a window needs you to drop elements from the front (they aged out) as well as the back (they're dominated).

Read the full intuition

Sliding-window-maximum, walk [1,3,-1,-3,5], k=3. Keep a deque of indices whose values are decreasing:

  • A new value pops every smaller value off the back (they can never be the max while this bigger one is around).
  • The front is always the window's max — but first check if it aged out (front <= i-k), and if so pop it from the front.

Each index is pushed once and popped once → O(n) for the whole sweep, versus O(n·k) brute force or O(n log n) with a heap.

Why it costs what it costs

Time O(n). each index is pushed once and popped once across the whole run; the inner while-loops are amortised O(1).

Space O(k). the deque holds at most one window's worth of candidate indices.

Practice

Next · Foundation

Sliding Window Maximum

Pop smaller from back, expired from front; front is the max.

0/9 solved
  • Sliding Window MaximumFoundationFoundationAmazon, GoogleHard
  • Sliding Window MinimumApply it · Minimum version at scale (generated input).Apply itCSESMedium
  • Longest Continuous Subarray With Absolute Diff Less Than or Equal to LimitOne change · Variable window with max and min.One changeMedium
  • Jump Game VICombine · DP transition over a window.CombineCitadel, AmazonMedium
  • Constrained Subsequence SumCombine · Same with optional restart.CombineHard
  • Shortest Subarray with Sum at Least KAdvanced · Negative values.AdvancedGoldman Sachs, CitadelHard
  • Max Value of EquationMastery checkMastery checkHard
  • Maximum Subarray Sum IICSESHard
  • Book Shop IICSESMedium

Pitfalls

Classic bugs

  • !Stored values instead of indices: you can't tell when the front expired (front <= i-k).
  • !<= vs < when popping the back decides how ties are kept; <= drops equal older values (usually right).
  • !Pop the stale front before reading the window's answer, not after.
  • !Record answers only once the first full window exists: i >= k-1.
  • !JS dq.shift() is O(n): for large n use an array with a head pointer.
Go deepervariants and techniques · 4 combinations · interviewer follow-ups · resources

Variants and techniques

  • Window maximum / minimumDecreasing deque for max, increasing for min; front is the answer. Sliding Window Maximum.
  • DP over last-k statesDeque of dp indices; dp[i] = value + best dp in window. Jump Game VI, Constrained Subsequence Sum.
  • Two deques togetherOne increasing + one decreasing to bound (max-min) within a window. Longest subarray with abs-diff ≤ limit.
  • Prefix-sum + dequeMonotonic deque over prefix sums for shortest/longest subarray with a sum constraint. Shortest Subarray with Sum at Least K.

Combinations

  • Sliding Window+Monotonic Deque

    subarray where max - min <= limit, or window extreme queries

    Sliding Window:
    two-pointer window boundaries
    Monotonic Deque:
    O(1) window max/min

    Longest Continuous Subarray With Absolute Diff Less Than or Equal to LimitSliding Window MaximumSliding Window Minimum

  • Prefix Sum+Monotonic Deque

    shortest subarray with sum >= K when values can be negative; max subarray sum with length in [a, b]

    Prefix Sum:
    subarray sums as prefix differences
    Monotonic Deque:
    keeps increasing prefix candidates for the left end

    Shortest Subarray with Sum at Least KMaximum Subarray Sum II

  • 1D / Fibonacci-style+Monotonic Deque

    jump at most k steps; subsequence with gaps at most k

    1D / Fibonacci-style:
    defines dp[i] from a range of previous states
    Monotonic Deque:
    range max of dp in amortised O(1)

    Jump Game VIConstrained Subsequence Sum

  • Bounded (Multiple) Knapsack+Monotonic Deque

    maximise value with up to c_i copies of item i, W ~ 1e5

    Bounded (Multiple) Knapsack:
    item counts c_i
    Monotonic Deque:
    sliding-window max of dp[r + j*w] - j*v over the last c_i positions of each residue

    Book Shop II

Follow-ups interviewers ask

  1. 01What if k changes with every query? → a sliding deque no longer fits; preprocess a sparse table for O(1) static range-max, or a segment tree if values update.
  2. 02What if the data is an infinite stream and you only keep the last k? → the deque already works online in O(1) amortised; just bound its memory to k.
  3. 03Could you do both min and max simultaneously (e.g. abs-diff ≤ limit)? → run two deques, one increasing, one decreasing.
  4. 04What if you need the window sum too? → keep a running sum alongside the deque; they compose.

State table

i x deque (indices) front expired? window max
0 1 [0] — (window not full)
1 3 [1] popped 0 (1≤3) (not full)
2 -1 [1,2] — 3
3 -3 [1,2,3] — 3
4 5 [4] popped 1,2,3 5

Resources

  • Queue & Stack explore cardLeetCode · course
  • Stack cheatsheetTech Interview Handbook · article
  • Minimum stack / minimum queuecp-algorithms · article
  • Sliding Window (monotonic deque)USACO Guide · course
  • NeetCode RoadmapNeetCode · sheet
Monotonic StackTrie (Prefix Tree)
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial