SystemTutor
About
Sign in
Loading course documentation…
SystemTutor

COURSES

  • Data Structures & Algorithms
  • CSS MasterclassNew course
  • System DesignNew course

PRACTICE

  • Algorithm practice
  • CSS practice

LEGAL

  • Privacy Policy
  • Terms of Service
  • About

© 2026 SystemTutor. All rights reserved.

Built with 🫶 by Shatlyk

Course Overview
Algorithm Patterns OverviewFrequency CountersTwo SumValid AnagramGroup AnagramsFrequency Counters and Hash-Map LookupTwo PointersValid PalindromeTwo Sum IIContainer With Most WaterTwo-Pointer ReasoningSliding WindowMaximum Average Subarray ILongest Substring Without Repeating CharactersMinimum Size Subarray SumSliding-Window Reasoning
Algorithm Patterns

Sliding Window

Learn how the sliding window pattern tracks contiguous ranges in arrays and strings while avoiding repeated work and quadratic nested loops.

The sliding window pattern keeps track of a continuous part of an array or string. The window moves across the input as one unit while we update only the values that enter or leave it.

A window can be represented by two indexes, a running total, a substring, or another small data structure. It usually moves from left to right:

A four-character window moves from a–d to b–e, dropping a and adding e.

Sliding windows are useful when a problem asks about a contiguous range: consecutive array values, neighboring characters, or a substring.

Core idea

When a window moves by one position, do not calculate the whole window again. Remove the value leaving the window and add the value entering it.

When this pattern fits

Look for a sliding window when:

  • The problem asks about a subarray, substring, or other contiguous range.
  • The window has a fixed size, such as “the largest sum of k consecutive values.”
  • The window has a changing size controlled by a condition, such as “the longest substring without duplicates.”
  • The next window overlaps most of the current window.

The two indexes are pointers to the edges of a contiguous interval. The values can be unsorted. For a variable-size window you also need a condition that tells you which edge can move safely.

Example: maximum sum of consecutive values

Write a function called maxSubarraySum that accepts an array of integers and an integer window size k. Return the largest sum of exactly k consecutive values. If k is less than one or exceeds the array length, return null in JavaScript or None in Python.

maxSubarraySum([2, 6, 9, 2, 1, 8, 5, 6, 3], 3)  → 19 ([8,5,6])
maxSubarraySum([4, 2, 1, 6], 4)                 → 13 (array length === 4)
maxSubarraySum([], 3)                           → null

The naive approach

The direct solution adds up each window from scratch. The first window's sum becomes the best sum so far. Each later window replaces it only if its sum is larger.

function maxSubarraySumNaive(numbers, size) {
  if (size < 1 || size > numbers.length) return null;

  let maximum = null;

  for (let start = 0; start <= numbers.length - size; start++) {
    let current = 0;

    for (let offset = 0; offset < size; offset++) {
      current += numbers[start + offset];
    }

    // A null maximum means this is the first window. Save its sum even if it is negative.
    if (maximum === null || current > maximum) {
      maximum = current;
    }
  }

  return maximum;
}

If the array has length n and the requested window has size k, this repeats up to k additions for each starting position. There are exactly n − k + 1 windows, each summed with k additions. A fixed k gives linear time. The total can grow quadratically when k is around half of n.

Build the first window

Start by adding the first size values. For [2, 6, 9, 2, 1, 8, 5, 6, 3] and a window size of 3, the first window is:

[2, 6, 9]  → 17

To move the window one position, subtract the value leaving on the left and add the value entering on the right:

[2, 6, 9] → [6, 9, 2]
17 - 2 + 2 = 17

[6, 9, 2] → [9, 2, 1]
17 - 6 + 1 = 12

The old values are not added again. Each slide performs only one subtraction and one addition.

The sliding-window solution

function maxSubarraySum(numbers, size) {
  if (size < 1 || size > numbers.length) return null;

  let windowSum = 0;

  for (let i = 0; i < size; i++) {
    windowSum += numbers[i];
  }

  let maximum = windowSum;

  for (let end = size; end < numbers.length; end++) {
    const start = end - size;
    windowSum += numbers[end] - numbers[start];
    maximum = Math.max(maximum, windowSum);
  }

  return maximum;
}

The first loop creates the initial window. The second loop slides it across the remaining values. Every array item is added once and removed at most once, so the total time is O(n) and the extra space is O(1).

maximum starts at the first real window sum instead of 0. This matters when all values are negative: the answer should remain negative rather than incorrectly becoming zero.

Variable-size windows

Not every window has a fixed size. Sometimes the window grows until it violates a condition, then shrinks from the left until it becomes valid again.

Longest substring without repeated characters

How long is the longest substring of "abcabcbb" with no repeated character? Step through the scan. The highlighted cells are the characters currently in the set. When the character at R is already in the set, L moves until the earlier copy leaves.

function longestUniqueSubstring(text) {
  const window = new Set();
  let left = 0;
  let longest = 0;

  for (let right = 0; right < text.length; right++) {
    while (window.has(text[right])) {
      window.delete(text[left]);
      left++;
    }

    window.add(text[right]);
    longest = Math.max(longest, right - left + 1);
  }

  return longest;
}

Enter up to 64 printable ASCII characters. Spaces count. An empty string is valid.

Step 1 of 15Max length 1
  1. Index 0a, highlighted↑L↑R
  2. Index 1b
  3. Index 2c
  4. Index 3a
  5. Index 4b
  6. Index 5c
  7. Index 6b
  8. Index 7b
Window
"a"
Left / Right
0 / 0
Current length
1

Step 1 of 15. Add “a” to the window.

Apply the same indexed window in the longest-substring practice.

The right pointer expands the window. When it would add a duplicate, the left pointer removes characters until the window is valid again. Although the code contains a for loop and a while loop, each character enters and leaves the window at most once, so the total time is O(n) with average constant-time set operations.

Fixed and variable windows

Window typeHow it movesTypical problem
Fixed sizeAdd one value and remove one value on every slideMaximum sum of k consecutive values
Variable sizeExpand and shrink until a condition is satisfiedLongest substring without repeated characters
Variable size with a sum thresholdRecord a qualifying length, then shrink while the sum still qualifiesShortest range reaching a target in a positive-valued array

For shortest-sum windows, positivity makes shrinking predictable: removing the first number always lowers the sum. With negative values, [1, -1, 5] at target 5 shows the problem. A window might record length three, drop the first 1, and stop shrinking at sum four, missing the final [5].

The window should represent exactly the part of the input that is currently being evaluated. Keeping that invariant clear makes it easier to decide what to add, what to remove, and when to update the answer.

Sliding window vs. repeated recalculation

ApproachMain methodTypical timeExtra space
Recalculate each rangeSum or inspect every item for every new windowO(k × (n − k + 1)) for fixed-width sumsO(1)
Sliding windowReuse the previous range and update its edgesO(n)O(1) or O(k)

For a variable-size window, a set or map may be needed to track the current contents, so space can grow with the window size.

Pattern checklist

Ask three questions: Is the target data contiguous? What information describes the current window? When the window moves, which value leaves and which value enters? If you can update the answer from those edge changes, a sliding window is likely a good fit.


Key Takeaways

  • Reuse Over Recalculate: Update only the values entering and leaving the window instead of recalculating the entire range from scratch.
  • Contiguous Data: Works on consecutive elements, subarrays, or substrings—the data does not need to be sorted.
  • Fixed vs. Variable Windows: Use fixed-size windows for exact lengths (like max sum of kkk items) and variable-size windows (expand right, shrink left) for condition-based targets.
  • Linear Time: Runs in O(n)O(n)O(n) time because every element enters and leaves the window at most once.
  • When to Choose: Use Sliding Window when dealing with contiguous ranges. If you need sorted pairs across opposite ends, use Two Pointers; if order does not matter, use a Frequency Counter.

How is this lesson?

Previous lessonTwo-Pointer ReasoningNext lessonMaximum Average Subarray I
Edit on GitHubReport on GitHub
On this page
%

On this page

When this pattern fitsExample: maximum sum of consecutive valuesThe naive approachBuild the first windowThe sliding-window solutionVariable-size windowsLongest substring without repeated charactersFixed and variable windowsSliding window vs. repeated recalculationKey Takeaways