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/Arrays & Two Pointers/Sliding Window

Learn the pattern · ~15 min

Sliding Window

also called caterpillar method, variable-size window

Keep one window that grows on the right and shrinks on the left, updating its summary one element at a time, so every element enters once and leaves once.

Signalslongest/shortest/count of contiguous subarray or substring satisfying a conditioncondition is monotone: if a window is valid, its sub-windows are valid (or vice versa)fixed window size kLearn firstTwo PointersHash Map / Hash Set Lookup
Cheat sheet and practice

Reach for it when you read

  • +Longest, shortest or count of contiguous subarrays or substrings that follow a rule.
  • +A fixed size k: the best sum, average or anagram over every window of length k.
  • +"At most k distinct", "at most k changes", "no repeats": a rule that only gets worse as the stretch grows.
  • +Your brute force fixes a start and extends an end, recomputing the same stretch again and again.

Not this one when

  • ×Sum exactly k with negative numbers allowed: prefix sum + hash map. Shrinking doesn't fix a sum that can go up or down.
  • ×A subsequence (elements may be skipped): usually DP, not a window.
  • ×The max or min inside every window: still a window, but you need a monotonic deque to answer it.

Learn Sliding Window

First, what is a "window"?

A window is a contiguous stretch of the array: everything from index left to index right, with nothing skipped. In [4, 2, 1, 3], the window left = 1, right = 2 is [2, 1]. [4, 1] is not a window, because it skips the 2.

A sliding window moves that stretch across the array. right steps forward every time, adding one element. left steps forward only when the window breaks a rule, removing one element. Both only ever move to the right.

How does the window move?

Take [4, 2, 1, 3, 1, 1, 5] and look for the longest window whose sum is at most 6. The rule is one line:

Add the next element. While the sum is over 6, remove from the left. Then the window is valid: measure it.

right add what happens window sum best
0 4 sum 4 is fine 4 4 1
1 2 sum 6 is fine 4, 2 6 2
2 1 sum 7 is over: remove 4 2, 1 3 2
3 3 sum 6 is fine 2, 1, 3 6 3
4 1 sum 7 is over: remove 2 1, 3, 1 5 3
5 1 sum 6 is fine 1, 3, 1, 1 6 4
6 5 sum 11 is over: remove 1, 3 and 1 1, 5 6 4

The answer is 4: [1, 3, 1, 1]. Notice the last row: one new element can force several removals.

The precondition

Why is removing from the left the right fix? Because here the rule only gets worse as the window grows. All the numbers are positive, so adding one can only raise the sum. Once [4, 2, 1] is over 6, every longer window starting at 4 is over 6 too. So left = 0 is finished for good, and moving left is the only thing that can help.

Without that property the window gives wrong answers. On [5, −4, 3] with "sum at most 4", the whole array sums to 4, so the answer is 3. The window drops 5 at once (5 > 4), never gets it back, and returns 2. Removing −4 would raise the sum, so shrinking stops being a fix. That kind of problem needs prefix sums, not a window.

The code for it

C++
int left = 0, sum = 0, best = 0;
for (int right = 0; right < n; right++) {
    sum += a[right];
    while (sum > S) sum -= a[left++];   // shrink until valid again
    best = max(best, right - left + 1);
}

You don't need to memorise this. It's the table: add on the right, remove on the left while broken, measure.

Why while and not if? In the last row, adding 5 made the sum 11, and it took three removals to get back to 6. An if would stop after one and measure a broken window.

Fine, but how does this help us?

The classic problem: Longest Substring Without Repeating Characters. Find the longest stretch of a string in which no letter appears twice.

Take "abcbdab" and solve it by hand. For each start, extend to the right until a letter repeats:

start longest stretch with no repeat length stopped by
0 abc 3 the second b
1 bc 2 the second b
2 cbda 4 the third b
3 bda 3 the third b
4 dab 3 end of the string
5 ab 2 end of the string
6 b 1 end of the string

The answer is 4: "cbda".

The brute force

The direct way is what we did by hand: from every start, extend until a letter repeats.

C++
int best = 0;
for (int i = 0; i < n; i++) {
    unordered_set<char> seen;
    for (int j = i; j < n && !seen.count(s[j]); j++) {   // stop at the first repeat
        seen.insert(s[j]);
        best = max(best, j - i + 1);
    }
}

How slow is it? A stretch with no repeat is at most σ long, where σ is the number of different characters, so each start takes at most σ + 1 steps: O(n·σ). Here (n ≤ 5 × 10⁴, at most 95 characters) that's under 5 × 10⁶ steps, and it passes. But ask for "the longest subarray with all values different" on numbers, and there's no small alphabet: if every value differs, each start walks to the end. That's n²/2 steps, 5 × 10⁹ for n = 10⁵. Time limit exceeded.

The one thought that fixes it

Stop at index 3, the second b. The window was abc, and now it's abcb: broken.

Which starts are still worth anything?

  • Start 0 (a…) or start 1 (b…): any window from there that reaches index 3 holds both b's. Making it longer later can't remove a letter, so it stays broken forever.
  • Start 2 (c…): the window cb holds one b. It's fine.

So starts 0 and 1 are dead. Drop letters from the left until the first b is gone, and carry on from cb. A repeat is a rule that only gets worse as the window grows, the same precondition as the sum, so it's the same loop: add on the right, shrink on the left while broken.

C++
unordered_map<char, int> count;
int left = 0, best = 0;
for (int right = 0; right < (int)s.size(); right++) {
    count[s[right]]++;
    while (count[s[right]] > 1) count[s[left++]]--;   // only the new letter can repeat
    best = max(best, right - left + 1);
}

Dry run

Same string, "abcbdab".

right letter removed window best
0 a none a 1
1 b none ab 2
2 c none abc 3
3 b a, b cb 3
4 d none cbd 3
5 a none cbda 4
6 b c, b dab 4

4, the same answer as the brute force.

Why it's O(n)

A while inside a for looks like O(n²). Count what happens to each index instead: right passes it once, adding it, and left passes it at most once, removing it. Both only move forward. So across the whole run there are at most n additions and n removals, about 2n steps: O(n) time. Space is one count per distinct letter.

From O(n·σ), or O(n²) when every value can differ, down to O(n), by never going back to a start that's already dead.

A fixed size k? No while loop

Maximum Average Subarray I: the best average over windows of exactly k = 4 elements. The size never changes, so once the window is full, each step adds one and removes one.

C++
sum += a[right];
if (right >= k) sum -= a[right - k];   // the element that just left the window
if (right >= k - 1) best = max(best, sum);

On [1, 12, −5, −6, 50, 3] the three windows sum to 2, 51 and 42, so the answer is 51 / 4 = 12.75. Negatives are fine here: nothing is ever decided by shrinking.

Count the windows? Add the length

How many windows of [4, 2, 1, 3, 1, 1, 5] have sum at most 6? If [left..right] is valid, then every window that ends at right and starts later is valid too: it's the same stretch with elements removed. That's right − left + 1 new windows.

C++
count += right - left + 1;   // every valid window that ends at right

The window lengths from the first table are 1, 2, 2, 3, 3, 4, 2, so the count is 17. Adding 1 per step would give 7.

The shortest instead of the longest? Shrink while it's valid

For "the shortest window with sum at least 7", the rule flips: a longer window is more likely to pass. So shrink while the window is valid, recording its length before each removal. On the same array the answer is 3: [4, 2, 1] or [1, 1, 5].

Exactly k? Two windows

"Sum exactly 6" isn't a rule that only gets worse: a window can go from too small to exactly right to too big. Count atMost(6) − atMost(5) instead, two plain windows. On our array that's 17 − 13 = 4: [4, 2], [2, 1, 3], [1, 3, 1, 1] and [1, 5]. The same trick counts subarrays with exactly k distinct values.

Remember this

  • Longest, shortest or count of contiguous stretches with a rule: a window, but only if the rule only gets worse as the window grows.
  • Negatives in a sum rule, or "sum equals k" in general: no window. Use prefix sums with a hash map.
  • while, not if, when shrinking. And measure after the window is valid again.
  • Whenever a problem asks "the longest/shortest subarray or substring such that…", try a sliding window first.

Practise it on Maximum Average Subarray I (fixed size), then Longest Substring Without Repeating Characters, Longest Repeating Character Replacement (at most k bad letters), Fruit Into Baskets (at most k distinct), Minimum Window Substring (shortest valid) and Subarrays with K Different Integers (exactly k).

Below, watch Longest Substring Without Repeating Characters run line by line.

Watch it work, line by line

Longest Substring Without Repeating Characters ↗, s = "abcabcbb" → 3 ("abc"). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Is the answer a contiguous stretch, can I add and remove one element cheaply, and does shrinking the window only ever make it more valid?

Reach for it when

  • +longest/shortest/count of contiguous subarray or substring satisfying a condition
  • +condition is monotone: if a window is valid, its sub-windows are valid (or vice versa)
  • +fixed window size k
  • +n up to 1e5-1e6
  • +values non-negative when the condition is a sum bound

It fails when

  • ×Elements can be skipped (subsequence, not contiguous)use Subsequence DP
  • ×Negative numbers with a sum target: growing can shrink the sum, validity isn't monotoneuse Prefix sum + hash map
  • ×Pairs from a sorted array hitting a targetuse Opposite-end two pointers
  • ×"Exactly K" constraint (exact counts aren't monotone)use atMost(K) − atMost(K−1) with two windows
  • ×You need the max/min of each windowuse Monotonic deque, not a counter
  • ×Window state can't be kept by simple add/removeuse Dynamic programming

Looks like it, isn't (and the other way round)

  • Subarray Sum Equals K looks like Sliding Window, needs Prefix Sum

    Negative numbers make window validity non-monotone; count prefix pairs with a hash map.

  • Subarray Sums Divisible by K looks like Sliding Window, needs Prefix Sum

    Divisibility is not monotone in window size; key prefix sums by residue.

  • Shortest Subarray with Sum at Least K looks like Sliding Window, needs Monotonic Deque

    Negatives break shrinking; keep a monotone deque of prefix sums.

  • Sum of Subarray Minimums looks like Sliding Window, needs Monotonic Stack

    No window condition; each element's contribution span comes from previous/next smaller.

  • Bitwise ORs of Subarrays looks like Sliding Window, needs Few Distinct Subarray OR / AND / GCD Values

    No window condition. The ORs ending at each index take only O(log V) values; carry that set forward.

Why this pattern and not another

You want the best contiguous subarray/substring under a constraint that updates incrementally as the window grows/shrinks — one O(n) pass, each element entering and leaving once.

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1What must be true of the rule for a variable window to work?Reveal

    Shrinking only makes the window more valid (and growing only less). Then left never needs to move back.

  • 2Longest valid window: where do you record the answer?Reveal

    After the shrink loop, once the window is valid again. For the shortest, inside the loop while it's still valid.

  • 3How do you count windows with exactly k distinct values?Reveal

    atMost(k) − atMost(k − 1). "Exactly" isn't monotone; "at most" is.

Practice ladder

every problem →
  1. 1Maximum Average Subarray Ifixed sizeEasy
  2. 2Longest Substring Without Repeating Charactersthe hookMedium
  3. 3Playlistno repeats, in disguiseMedium
  4. 4Longest Repeating Character Replacementat most k badMedium
  5. 5Fruit Into Basketsat most k distinctMedium
  6. 6Permutation in Stringfixed size, countsMedium
  7. 7Minimum Window Substringmust contain everythingHard
  8. 8Subarrays with K Different Integersexactly kHard

Finished Sliding Window? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Sliding Window

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial