Sliding Window in Arrays — A Beginner’s Mental Model

Published: (February 8, 2026 at 04:04 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

What Is a Sliding Window?

A sliding window is a technique for processing a continuous part of an array (or string) while reusing previous calculations.
Instead of recomputing everything for each new subarray, you:

  1. Compute the result for the first window.
  2. Slide the window forward by removing the element that leaves and adding the element that enters.

That’s it.

When to Use a Sliding Window

Use it whenever a problem asks for something about a subarray / substring, especially when the statement mentions:

  • “subarray of size K
  • “maximum/minimum sum of any K‑length window”

In such cases, a naïve approach would:

  • Loop over every possible subarray.
  • Re‑sum all elements each time → O(N·K) time.

With a sliding window you achieve O(N) time by updating the result incrementally.

Example

Consider the array:

[5, 2, 7, 1]
K = 3

First window ([5, 2, 7]) → Sum = 14

Slide one step

  • Leaving element: 5
  • New window: [2, 7, 1]
  • Updated sum: 14 - 5 + 1 = 10

No full recalculation is needed.

How Pointer Movement Works

Fixed‑size sliding window

Let k be the window size. For each step i (starting at i = k):

  • Leaving element = arr[i - k]
  • Entering element = arr[i]

You don’t need an explicit “left pointer”; the arithmetic takes care of it.

Sample Code (C++)

double maxSumSubarray(vector nums, int k) {
    int windowSum = 0;

    // first window
    for (int i = 0; i (maxSum) / k;
}

If you can explain the steps above clearly, you can translate them into code for any language.

Example Input to Validate Your Understanding

nums = [1, 12, -5, -6, 50, 3]
k = 4

The windows are:

  1. [1, 12, -5, -6]
  2. [12, -5, -6, 50]
  3. [-5, -6, 50, 3]

Each slide removes one element and adds one new element, allowing the sum (or any aggregate) to be updated with a simple subtract + add operation. No extra loops are required.

Key Takeaway

The sliding‑window technique isn’t magic; it’s simply:

“Reuse the previous result by removing what leaves and adding what enters.”

By doing so, you avoid redundant calculations and achieve linear‑time solutions for many subarray/subsequence problems.

0 views
Back to Blog

Related posts

Read more »

HTML starter

Introduction Welcome to the HTML Starter series. In this series I’ll share everything I’ve learned about web development up to 2026. Let’s get started! Setup 1...

Problem 13: Group Anagrams

Overview The task is to write a function that groups words that are anagrams of each other from a given list of strings. An anagram is a word or phrase formed...