First published on CodeKairo, where the figures in this lesson are animated step by step.

In short: The sliding window technique keeps one contiguous stretch of an array or string, the window, and updates its sum, count or contents as its edges move, instead of recomputing every subarray from scratch. A fixed window slides one step at a time; a variable window grows on the right and shrinks on the left. Each element enters and leaves the window at most once, so the scan takes O(n) time.

Many questions ask about a contiguous stretch of the input: the largest sum of k consecutive numbers, the longest substring with no repeated letter. Neighbouring stretches share almost all their elements, so the sliding window technique keeps one stretch, the window, and updates it as the edges move — O(1) a step instead of O(k). It is two pointers moving the same way, in two kinds:

Figure: The two kinds of sliding window

Top: a window of fixed length k moves one step, so one element enters and one leaves, and its sum updates in O(1). Bottom: a window obeying a rule ("no repeated letter") grows by moving right and shrinks by moving left; both only ever move forwards.

Why recomputing every window is too slow

Summing every window of k from scratch is n − k + 1 windows of k additions: about 2.5 × 10⁹ for n = 100,000 and k = 50,000, against roughly 10⁸ simple steps a second. Without a fixed length it is worse — about n²/2 substrings, each checked for repeats. Yet neighbouring windows share k − 1 elements, added up again every time.

The idea: slide the window instead of rebuilding it

A fixed-size window keeps a running sum: old sum + newcomer − leaver. Given a rule instead of a length, a variable-size window from left to right follows three rules:

  • Grow. Move right one step and add the new element to the window's state.
  • Shrink. While the window breaks the rule, remove the element at left and move left on.
  • Record. Once the window obeys the rule again, compare it with the best so far.

The state is whatever checks the rule in O(1): a running sum, or a count map of how often each value is inside. Below, the longest substring without a repeat in "pwwkew" — where a map of last-seen positions lets left jump straight past a repeat.

▶ The step-by-step walkthrough for this topic is on CodeKairo.

A fixed-size window

There is nothing to decide: build the first window once, then slide it to the end. When right enters, the element leaving is arr[right - k] and the window starts at right - k + 1.

Figure: A fixed-size window: add the newcomer, subtract the leaver — arr = [2, 1, 5, 1, 3, 2], k = 3

  1. Build the first window once: 2 + 1 + 5 = 8. That costs k additions — the only time the window is summed from scratch.
  2. Slide one step: 1 enters and 2 leaves, so the sum is 8 − 2 + 1 = 7. The 2 elements both windows share are never added again — the brute force would add them all over.
  3. 3 enters, 1 leaves: 7 − 1 + 3 = 9. That beats every window so far: best = 9.
  4. 2 enters, 5 leaves: 9 − 5 + 2 = 6. Not better than 9.
  5. The best window is 2..4 with sum 9. Every window after the first cost one addition and one subtraction, whatever k is: O(n) in all, against O(n × k) for summing each window afresh.

▶ Watch this figure animated, step by step

The code

The program runs the same array with k = 3 and k = 2. With k = 2 two windows tie at 6; the strict > keeps the first one.

C++

#include <iostream> #include <utility> #include <vector> using namespace std; // Largest sum of k consecutive elements, and the index where that window starts. pair<int, int> maxWindowSum(const vector<int>& arr, int k) { int sum = 0; for (int i = 0; i < k; i++) sum += arr[i]; // the first window, built once int best = sum, bestStart = 0; for (int right = k; right < (int)arr.size(); right++) { sum += arr[right] - arr[right - k]; // one element enters, one leaves if (sum > best) { best = sum; bestStart = right - k + 1; } } return {best, bestStart}; } int main() { vector<int> arr = {2, 1, 5, 1, 3, 2}; for (int k : {3, 2}) { pair<int, int> r = maxWindowSum(arr, k); cout << "k = " << k << ": best sum " << r.first << " (indices " << r.second << " to " << r.second + k - 1 << ")\n"; } return 0; } 

Java

public class Main { // Largest sum of k consecutive elements, and the index where that window starts. static int[] maxWindowSum(int[] arr, int k) { int sum = 0; for (int i = 0; i < k; i++) sum += arr[i]; // the first window, built once int best = sum, bestStart = 0; for (int right = k; right < arr.length; right++) { sum += arr[right] - arr[right - k]; // one element enters, one leaves if (sum > best) { best = sum; bestStart = right - k + 1; } } return new int[] {best, bestStart}; } public static void main(String[] args) { int[] arr = {2, 1, 5, 1, 3, 2}; for (int k : new int[] {3, 2}) { int[] r = maxWindowSum(arr, k); System.out.println("k = " + k + ": best sum " + r[0] + " (indices " + r[1] + " to " + (r[1] + k - 1) + ")"); } } } 

Python

def max_window_sum(arr, k): """Largest sum of k consecutive elements, and the index where that window starts.""" total = sum(arr[:k]) # the first window, built once best, best_start = total, 0 for right in range(k, len(arr)): total += arr[right] - arr[right - k] # one element enters, one leaves if total > best: best = total best_start = right - k + 1 return best, best_start arr = [2, 1, 5, 1, 3, 2] for k in (3, 2): best, start = max_window_sum(arr, k) print(f"k = {k}: best sum {best} (indices {start} to {start + k - 1})") 

JavaScript

// Largest sum of k consecutive elements, and the index where that window starts. function maxWindowSum(arr, k) { let sum = 0; for (let i = 0; i < k; i++) sum += arr[i]; // the first window, built once let best = sum; let bestStart = 0; for (let right = k; right < arr.length; right++) { sum += arr[right] - arr[right - k]; // one element enters, one leaves if (sum > best) { best = sum; bestStart = right - k + 1; } } return [best, bestStart]; } const arr = [2, 1, 5, 1, 3, 2]; for (const k of [3, 2]) { const [best, start] = maxWindowSum(arr, k); console.log(`k = ${k}: best sum ${best} (indices ${start} to ${start + k - 1})`); } 

Output

k = 3: best sum 9 (indices 2 to 4) k = 2: best sum 6 (indices 1 to 2) 

The same slide answers Maximum Sum Subarray of Size K. Permutation in String is a fixed window too: slide a pattern-length window across the text and compare its letter counts with the pattern's.

A variable-size window: grow, then shrink

The classic is Longest Substring Without Repeating Characters, with a count map as the state. The window was valid before s[right] arrived, so a count of 2 can only be the newcomer's: shrink until it is 1 again. This is the program's loop, without the last-seen jump:

Figure: Grow, then shrink: the longest substring without a repeat — s = "abcabcbb"

  1. right = 0: 'a' enters, its count is 1, and the window "a" is valid. The count map is the window's state: how many times each letter is inside.
  2. right = 1: 'b' enters with count 1 — still no repeat. The window "ab" has length 2, the longest yet.
  3. right = 2: 'c' enters with count 1 — still no repeat. The window "abc" has length 3, the longest yet.
  4. right = 3: 'a' now appears twice. Only the newcomer can be the repeat, so drop from the left until its count is 1: 'a' goes. The window "bca" has length 3.
  5. right = 4: 'b' appears twice again, and its first copy is at the left edge: drop 'b'. The window "cab" has length 3.
  6. right = 5: 'c' appears twice again, and its first copy is at the left edge: drop 'c'. The window "abc" has length 3.
  7. right = 6: 'b' appears twice, but its first copy is not at the left edge, so 'a' and 'b' both go before its count is 1. The window "cb" has length 2.
  8. right = 7: 'b' appears twice, but its first copy is not at the left edge, so 'c' and 'b' both go before its count is 1. The window "b" has length 1.
  9. The longest is 3, "abc". right moved 8 times and left moved 7 times, each element entering once and leaving at most once: O(n), despite the loop inside the loop.

Why shrinking is safe

left never moves back, so once it passes an index no later window starts there. That cannot miss the answer because the rule is monotone: a repeat-free window stays so when shrunk, and a window with a repeat keeps it when grown:

Figure: Why shrinking is safe: the best start never moves back — s = "abcabcbb"

  1. Each cell is one window: start by row, right end by column, its length written in when it has no repeated letter (teal). The brute force checks all 36 windows.
  2. The rule is monotone: a window with no repeat stays repeat-free when shrunk, and one with a repeat keeps it when grown. So down each column the valid windows form one block, ending at the diagonal — here the column for right = 6.
  3. The top of each block is the best start for that right end, and as right moves on it never moves up: 0, 0, 0, 1, 2, 3, 5, 7. So left can be carried forward instead of restarting — at most n moves in all.
  4. The answer is the tallest block, length 3, first at right = 2. The loop walks only the staircase — about 2n steps — and never looks at the 18 broken windows above it.

That is the loop's invariant: after the shrink loop, the window from left to right is the longest valid window ending at right. Every substring ends somewhere, so the best over all right is the best overall. Before writing any window, ask: does shrinking a valid window keep it valid? If not, the window is the wrong tool.

The code

The program records only a strictly longer window, so for "pwwkew" it reports "wke", the first of the two longest answers.

C++

#include <iostream> #include <string> #include <unordered_map> using namespace std; // Longest substring of s with no repeated character, found by grow-then-shrink. string longestDistinct(const string& s) { unordered_map<char, int> count; // how many times each character is in the window int left = 0, bestLeft = 0, bestLen = 0; for (int right = 0; right < (int)s.size(); right++) { count[s[right]]++; // grow: s[right] enters while (count[s[right]] > 1) { // shrink until the window is valid again count[s[left]]--; left++; } if (right - left + 1 > bestLen) { // valid here: record it bestLen = right - left + 1; bestLeft = left; } } return s.substr(bestLeft, bestLen); } int main() { for (string s : {"abcabcbb", "bbbbb", "pwwkew"}) { string best = longestDistinct(s); cout << "\"" << s << "\" -> " << best.size() << " (\"" << best << "\")\n"; } return 0; } 

Java

import java.util.HashMap; import java.util.Map; public class Main { // Longest substring of s with no repeated character, found by grow-then-shrink. static String longestDistinct(String s) { Map<Character, Integer> count = new HashMap<>(); // how many times each character is in the window int left = 0, bestLeft = 0, bestLen = 0; for (int right = 0; right < s.length(); right++) { char in = s.charAt(right); count.merge(in, 1, Integer::sum); // grow: s[right] enters while (count.get(in) > 1) { // shrink until the window is valid again count.merge(s.charAt(left), -1, Integer::sum); left++; } if (right - left + 1 > bestLen) { // valid here: record it bestLen = right - left + 1; bestLeft = left; } } return s.substring(bestLeft, bestLeft + bestLen); } public static void main(String[] args) { for (String s : new String[] {"abcabcbb", "bbbbb", "pwwkew"}) { String best = longestDistinct(s); System.out.println("\"" + s + "\" -> " + best.length() + " (\"" + best + "\")"); } } } 

Python

def longest_distinct(s): """Longest substring of s with no repeated character, found by grow-then-shrink.""" count = {} # how many times each character is in the window left = best_left = best_len = 0 for right, ch in enumerate(s): count[ch] = count.get(ch, 0) + 1 # grow: s[right] enters while count[ch] > 1: # shrink until the window is valid again count[s[left]] -= 1 left += 1 if right - left + 1 > best_len: # valid here: record it best_len = right - left + 1 best_left = left return s[best_left:best_left + best_len] for s in ("abcabcbb", "bbbbb", "pwwkew"): best = longest_distinct(s) print(f'"{s}" -> {len(best)} ("{best}")') 

JavaScript

// Longest substring of s with no repeated character, found by grow-then-shrink. function longestDistinct(s) { const count = new Map(); // how many times each character is in the window let left = 0; let bestLeft = 0; let bestLen = 0; for (let right = 0; right < s.length; right++) { const ch = s[right]; count.set(ch, (count.get(ch) || 0) + 1); // grow: s[right] enters while (count.get(ch) > 1) { // shrink until the window is valid again count.set(s[left], count.get(s[left]) - 1); left++; } if (right - left + 1 > bestLen) { // valid here: record it bestLen = right - left + 1; bestLeft = left; } } return s.slice(bestLeft, bestLeft + bestLen); } for (const s of ["abcabcbb", "bbbbb", "pwwkew"]) { const best = longestDistinct(s); console.log(`"${s}" -> ${best.length} ("${best}")`); } 

Output

"abcabcbb" -> 3 ("abc") "bbbbb" -> 1 ("b") "pwwkew" -> 3 ("wke") 

For a small known alphabet, an array of counts indexed by character code (26 or 1...