DSA Tracker

Hard

Sliding Window Maximum (Two Pointers)

A hard Sliding Window problem included in Apna College, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Sliding Window
Sheets
2
Core for
5 roles
Platform
LeetCode

The problem

Given an array of integers and a sliding window of size k, return an array of the maximum value in each window as it slides from left to right.

Example 1

Input
nums = [1,3,-1,-3,5,3,6,7], k = 3
Output
[3,3,5,5,6,7]
Why
Window [1,3,-1] max=3, [3,-1,-3] max=3, [-1,-3,5] max=5, [-3,5,3] max=5, [5,3,6] max=6, [3,6,7] max=7.

Example 2

Input
nums = [1], k = 1
Output
[1]

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= nums.length

How to think about it

Updated 2026-09-09

An element that enters the window is both newer and potentially larger than older entries. Whenever a new number exceeds earlier numbers currently in the span, those older values can never serve as the window maximum again. Keeping only candidates in strictly descending order sheds useless values immediately and keeps the current leader at the front.

Approaches, worst first

  1. Scan each span

    time O(n * k) · space O(1)

    Recompute the maximum across all k slots for every starting position. Simple to write, but completely ignores the k - 1 elements shared between adjacent windows.

  2. Max-heap with indices

    time O(n log n) · space O(n)

    Store value-index pairs in a priority queue and discard the top whenever its index falls outside the current window. Correct, but pays a logarithmic penalty on every insertion and eviction.

  3. Monotonic deque of indicesWrite this one

    time O(n) · space O(k)

    Maintain indices in a double-ended queue where values stay strictly decreasing. Pop smaller items from the back before inserting, drop expired indices from the front, and read the front as the window maximum. Each index enters and leaves at most once.

Where people lose marks · 3
  • Storing raw values in the deque instead of their indices makes it impossible to tell whether the front element has expired past the left boundary.
  • Popping from the back using greater-or-equal instead of strictly greater allows duplicate maximum values to survive, breaking strict monotonicity.
  • Emitting maximums before the first k elements have been ingested adds garbage outputs for incomplete initial windows.

The theory behind it

Sliding Window — the ground this problem stands on. All Sliding Window problems

What Sliding Window is

A sliding window is an adjustable magnifying lens placed over a continuous segment of a sequence. Rather than recalculating metrics for every potential subsection from scratch, the window expands rightward by absorbing fresh elements and contracts leftward to expel stale entries. Only data currently framed within the window borders contributes to the active calculation.

When to reach for it

Reach for a sliding window when a question asks for the longest, shortest, or optimal contiguous subarray or substring matching a constraint. Key signals include fixed window sizes like maximum sum across k consecutive values, or dynamic criteria like finding the shortest substring holding all target characters. If the target subset must form an unbroken continuous run, window mechanics replace repetitive segment rescanning.

How the pattern works

Maintain two boundary indices, left and right, defining the active interval alongside a running state accumulator. In each step, expand the right boundary to incorporate the incoming element into state totals. When current state violates the designated problem constraints, increment the left boundary while deducting departing values until validity is restored. Update your tracking metric, whether minimum window length or maximum score, only during valid intervals.

What each operation costs

OperationTime
slide window across full array lengthO(n)
update running aggregate per incoming elementO(1)
auxiliary window frequency map storageO(k)
What usually goes wrong with Sliding Window
  • Shrinking the left border using an if statement instead of a while loop, allowing invalid window conditions to persist across iterations.
  • Updating optimum results before validating window legality, recording illegal states that contain duplicate items or violate length requirements.
  • Forgetting to decrement left element frequencies or remove empty keys from tracking maps when advancing the left boundary forward.

Which roles need this problem

Sliding Window is a core topic for these 5 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 10 more roles, including SDE / Backend Engineer, Data Engineer, ML Engineer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Sliding Window problems

Problem set and role mapping as of .