AlgoTales · Roadmap

Sliding-window maximum/minimum

Advanced · 12 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Sliding-window maximum or minimum reports the biggest or smallest value inside a fixed-size window as it moves along a list. A monotonic queue keeps only the useful candidates, so each step costs almost nothing, even for large windows.

Practical use cases

  • Web app: Best over in a cricket match feed. A live cricket page shows the highest runs scored in any 3-over stretch as the match goes on. Each new over drops one from the window and adds another. A queue of candidate overs gives the best stretch from its front at once, without re-adding the last three overs each time.
  • Web app: Rolling peak load on an admin dashboard. A hosting dashboard charts the highest visitor count in any 10-minute window across a whole day. Rescanning 10 values for each of 1,440 minutes is fine for one site, but it gets heavy for 10,000 sites and wider windows. A queue of candidate peaks keeps each minute cheap.
  • System: Video and sensor analytics. Video tools smooth or analyse frames by looking at the brightest or darkest value in a moving group of pixels or frames. Weather and industrial sensors report rolling highs and lows the same way, often on small devices where every saved step matters.

The story: The Cricket Commentator's Best Over

Commentator Ramesh Uncle loved statistics. During a long cricket match he wanted to announce, after every ball, the highest run total among the last 3 overs. The scorer Zoya had a long list of runs per over and Ramesh kept asking, "Zoya, what is the best of the last three?"

Zoya's first plan: look at the last three numbers and pick the biggest, again and again. With a window of three that is fine. But the next match was a Test where Ramesh wanted "the best of the last 500 overs". Looking at 500 numbers after every over was too slow for live TV.

Mira was sitting next to them, eating chips. "Zoya didi, remember the monotonic queue? Keep a short list of indexes in decreasing order of runs. When a big over arrives, kick out the smaller ones from the back: they will never be the best. When an index falls outside the window, remove it from the front. The front is always the answer." Zoya tried it, and every over now needed a tiny constant amount of work. Ramesh announced records faster than the scoreboard.

How to spot this problem, and where you need it

You must report the maximum or minimum of every group of k consecutive values in a long list, and recomputing it by scanning each group wastes time as groups and lists grow.

Signs you need it

  • The phrase "every window of size k", "rolling maximum", "peak in the last N" or "best stretch of K days" appears.
  • You use a loop inside a loop, with an inner loop over exactly k elements for each starting position.
  • Larger windows make the code much slower, even though neighbouring windows differ by only one element.

Where to use it in a project

  • Rolling highs and lows in monitoring, finance and sports statistics pages.
  • Peak-load or best-period reports on admin dashboards, such as busiest ten minutes of the day.
  • Signal, video and sensor smoothing or analysis where a window slides over many readings.

The solution

Keep a queue of positions inside the window, with their values in decreasing order. For each new value, remove from the back all smaller values, then add the new one. If the front position has fallen outside the window, remove it. After the first full window, record the value at the front as that window's maximum. For a minimum, flip the comparison.

Payoff: Before: 1,000,000 values with a window of 100 meant about 100 million checks. After: roughly 2 million steps.

Explain it like I am 8

Imagine a row of kids and a magic picture frame that shows three kids at a time. As the frame slides, you only keep a note of the kids who could still be the tallest. A taller newcomer makes the shorter kids in your note useless, so you cross them out. The first name in your note is the answer.

How it works, step by step

  1. Make an empty deque of indexes (not values), because indexes tell you whether an item has left the window.
  2. For each position i: if the index at the front is older than the window (front <= i - k), remove it from the front.
  3. While the value at the back of the deque is smaller than nums[i], remove it from the back. Then add i.
  4. Once the first window is full (i >= k - 1), the front of the deque points at the maximum: record nums[front].
  5. For the minimum, flip the comparison so the deque keeps increasing values instead.

The code in four languages

PHP

<?php
// Maximum (or minimum) of every window of size $k, in one pass.
function slidingWindow(array $nums, int $k, bool $wantMax = true): array {
    $dq = [];          // indexes; values are monotonic from front to back
    $head = 0;         // front pointer into $dq
    $out = [];
    foreach ($nums as $i => $x) {
        // 1) drop the front index if it slid out of the window
        if (count($dq) > $head && $dq[$head] <= $i - $k) $head++;
        // 2) drop back indexes that can never be the answer again
        while (count($dq) > $head) {
            $last = $nums[end($dq)];
            $useless = $wantMax ? $last < $x : $last > $x;
            if (!$useless) break;
            array_pop($dq);
        }
        $dq[] = $i;
        // 3) the window is full: the front holds the answer
        if ($i >= $k - 1) $out[] = $nums[$dq[$head]];
    }
    return $out;
}

$nums = [1, 3, -1, -3, 5, 3, 6, 7];
echo 'max: ' . implode(', ', slidingWindow($nums, 3)) . "\n";         // 3, 3, 5, 5, 6, 7
echo 'min: ' . implode(', ', slidingWindow($nums, 3, false)) . "\n";  // -1, -3, -3, -3, 3, 3

JavaScript

// Maximum (or minimum) of every window of size k, in one pass.
function slidingWindow(nums, k, wantMax = true) {
  const dq = [];       // indexes; values are monotonic from front to back
  let head = 0;        // front pointer into dq
  const out = [];
  nums.forEach((x, i) => {
    // 1) drop the front index if it slid out of the window
    if (dq.length > head && dq[head] <= i - k) head++;
    // 2) drop back indexes that can never be the answer again
    while (dq.length > head) {
      const last = nums[dq[dq.length - 1]];
      const useless = wantMax ? last < x : last > x;
      if (!useless) break;
      dq.pop();
    }
    dq.push(i);
    // 3) the window is full: the front holds the answer
    if (i >= k - 1) out.push(nums[dq[head]]);
  });
  return out;
}

const nums = [1, 3, -1, -3, 5, 3, 6, 7];
console.log('max: ' + slidingWindow(nums, 3).join(', '));          // 3, 3, 5, 5, 6, 7
console.log('min: ' + slidingWindow(nums, 3, false).join(', '));   // -1, -3, -3, -3, 3, 3

Java

import java.util.*;

public class Main {
    // Maximum (or minimum) of every window of size k, in one pass.
    static List<Integer> slidingWindow(int[] nums, int k, boolean wantMax) {
        Deque<Integer> dq = new ArrayDeque<>();    // indexes; values are monotonic from front to back
        List<Integer> out = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            int x = nums[i];
            // 1) drop the front index if it slid out of the window
            if (!dq.isEmpty() && dq.peekFirst() <= i - k) dq.pollFirst();
            // 2) drop back indexes that can never be the answer again
            while (!dq.isEmpty()) {
                int last = nums[dq.peekLast()];
                boolean useless = wantMax ? last < x : last > x;
                if (!useless) break;
                dq.pollLast();
            }
            dq.addLast(i);
            // 3) the window is full: the front holds the answer
            if (i >= k - 1) out.add(nums[dq.peekFirst()]);
        }
        return out;
    }

    static String join(List<Integer> values) {
        StringJoiner sj = new StringJoiner(", ");
        for (int v : values) sj.add(String.valueOf(v));
        return sj.toString();
    }

    public static void main(String[] args) {
        int[] nums = {1, 3, -1, -3, 5, 3, 6, 7};
        System.out.println("max: " + join(slidingWindow(nums, 3, true)));    // 3, 3, 5, 5, 6, 7
        System.out.println("min: " + join(slidingWindow(nums, 3, false)));   // -1, -3, -3, -3, 3, 3
    }
}

Go

package main

import (
	"fmt"
	"strconv"
	"strings"
)

// slidingWindow returns the maximum (or minimum) of every window of size k, in one pass.
func slidingWindow(nums []int, k int, wantMax bool) []int {
	var dq []int // indexes; values are monotonic from front to back
	head := 0    // front pointer into dq
	var out []int
	for i, x := range nums {
		// 1) drop the front index if it slid out of the window
		if len(dq) > head && dq[head] <= i-k {
			head++
		}
		// 2) drop back indexes that can never be the answer again
		for len(dq) > head {
			last := nums[dq[len(dq)-1]]
			useless := last > x
			if wantMax {
				useless = last < x
			}
			if !useless {
				break
			}
			dq = dq[:len(dq)-1]
		}
		dq = append(dq, i)
		// 3) the window is full: the front holds the answer
		if i >= k-1 {
			out = append(out, nums[dq[head]])
		}
	}
	return out
}

func join(nums []int) string {
	parts := make([]string, len(nums))
	for i, v := range nums {
		parts[i] = strconv.Itoa(v)
	}
	return strings.Join(parts, ", ")
}

func main() {
	nums := []int{1, 3, -1, -3, 5, 3, 6, 7}
	fmt.Println("max: " + join(slidingWindow(nums, 3, true)))  // 3, 3, 5, 5, 6, 7
	fmt.Println("min: " + join(slidingWindow(nums, 3, false))) // -1, -3, -3, -3, 3, 3
}

Time: O(n) · Extra space: O(k). Every index enters the deque once and leaves once, and the deque never holds more than one window of indexes.

Watch out for

  • Storing values instead of indexes, so you cannot tell when the front has slid out of the window.
  • Forgetting to remove the expired front index before reading the answer.
  • Recording answers before the first window is full (when i < k - 1).

Quick check

  1. Why does the deque store indexes and not just values?
    • To save memory
    • To sort the array
    • To know when an item has left the window
  2. For the sliding window <em>minimum</em>, what changes?
    • You flip the comparison so the deque keeps increasing values
    • Nothing
    • You need two deques
  3. Time complexity of this method for n numbers?
    • O(n)
    • O(n × k)
    • O(n log n)