Pattern 2: Sliding Window Technique

Hey guys, welcome to my DSA Pattern series! If you are new here, you can have a quick glance at my past posts. Today, let’s break down the Sliding Window technique. This is the pattern that hits mostly as the first question in an interview at least, if I were an interviewer, I would go with this question to ease the mind of the candidate. Let’s get into it with a story:

Cards Game:

On a chilling day without adventure, the Straw Hats played a game. Basically, there are two opponents Nami and Robin and the remaining Straw Hats are placing bets. Let’s get into the game:

Both teams are given cards numbered from 1 to 30, arranged in a non-consecutive zigzag manner, but both players receive them in the same order. They need to find the maximum sum of 6 consecutive cards. Whoever finds the maximum sum first wins!

(If the problem sounds lame — gomen, guys! That means “sorry” in Japanese.)

Cards Game [AI Generated]

Nami’s Approach:

What Nami tries to do is pick the first card and sum it with the next five cards, then write that answer on a paper. Then she picks the second card and sums it with the next five cards. If it is greater than the previous sum, she updates the answer to the current sum.

If I formulate this in a programming language, let A be the array of card numbers in the given order:

int answer = 0;
for (int i = 0; i < 30; i++) {
int sum = 0;
for (int j = i; j < i + 6 && j < 30; j++) {
sum += A[j];
}
answer = max(sum, answer);
}

In real life, we tend to go with this solution first — this is the naive approach. However, it takes more time because for every card, she is adding the next five consecutive cards, and then going back to the next starting card and repeating the same work all over again. This is repetitive work.

Robin’s Approach:

Robin, on the other hand (she is not using her Devil Fruit powers here!) does something smarter. She picks the first 6 cards and writes their sum on paper. From the next step onwards, she subtracts the first card of the current window and adds the next new card, then compares the new sum with the previous answer. If the new sum is greater, she updates the answer; otherwise, she keeps the old answer.

What Robin is doing here is fixing a group of 6 consecutive cards — this is called the window. Then she removes the first card and adds the 7th card, so the window slides from positions 1–6 to positions 2–7. This movement is called sliding. In general, what we do is fix the window and slide it forward to avoid repetitive steps and this is called the Sliding Window technique!

Let me formulate this in a programming language:



int k = 6; // window size
int n = A.size();

// Step 1: Find sum of first window
int windowSum = 0;
for (int i = 0; i < k; i++) {
windowSum += A[i];
}

int maxSum = windowSum;

// Step 2: Slide the window
for (int i = k; i < n; i++) {
// Remove first element of previous window
windowSum -= A[i - k];

// Add new element
windowSum += A[i];

// Update max sum
maxSum = max(maxSum, windowSum);
}

There are a few variants in the sliding window technique based on how the window moves and how its size changes. Each variant solves a different kind of problem, but they all share the same core idea a left pointer and a right pointer moving through the array. Let us go through each one clearly.

Variant 1 — Constant Window :
The simplest variant. Here the window size is fixed from the start and never changes you just slide it forward one step at a time.

For example think of it like this You own a tea shop and you want to find which 3 consecutive days had the highest tea sales. You do not check every possible combination — you simply place a frame of 3 days, note the total, then slide the frame one day forward and note the total again. Day 1–3, then Day 2–4, then Day 3–5, and so on until you reach the end. The window size stays 3 throughout. You never grow it, you never shrink it. You just move it.

Constant window variant[AI Generated]

Practice Problems:

  • Maximum Average Subarray I
  • Maximum Sum of Distinct Subarrays With Length K
  • Contains Duplicate II
  • Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
  • Sliding Window Maximum

Note: Use this variant when the problem gives you a fixed size k and asks for the best result across every window of that size.

Variant 2 — Variable Window (condition ≤ k) :
Now the window size is no longer fixed. It grows and shrinks based on a condition. This is the most common variant you will face in interviews, so understanding it well is important.
Let’s Think of it like being at a buffet. You keep adding food to your plate one item at a time, but you have a calorie limit you cannot cross. As long as the total calories are within the limit, you keep adding. The moment you cross it, you remove the item you added first the one sitting at the bottom of your plate and check again. You keep doing this and at every valid moment you record how many items are on your plate. Your goal is to find the maximum number of items you can have at once without crossing the limit.
In terms of pointers the right hand keeps adding, the left hand removes when things go wrong. The window grows when valid and shrinks when the condition breaks.

Variable Window [AI Generated]

Practice Problems:

  • Longest Substring Without Repeating Characters
  • Fruit Into Baskets
  • Longest Repeating Character Replacement
  • Max Consecutive Ones III
  • Permutation in String

Note: Use this variant when the problem asks for the longest subarray or substring where a condition stays within a limit.

Variant 3 — Count Subarrays where condition == exactly k :
This variant is about counting. Specifically, counting how many subarrays satisfy an exact condition — not “at most”, not “at least”, but exactly k. And this is where things get interesting.
For example Imagine students sitting in a long row. Some wear spectacles, some do not. A consecutive group simply means any continuous stretch of students without skipping anyone. Your task is to count how many such groups contain exactly 2 students wearing spectacles. Your first instinct might be to use a sliding window directly expand right, shrink left when you exceed 2. But here is the problem. When a third spectacle student enters, the window becomes invalid and you shrink from the left. If you remove a non-spectacle student, you still have 3 — still invalid. If you remove a spectacle student, you drop to 2 — valid again.

The window keeps flipping between valid and invalid unpredictably, and you lose track of what to count and when. This is why “exactly k” does not behave smoothly inside a sliding window on its own. So instead, we borrow the idea from Variant 2 where “at most k” works perfectly because the window has one clean boundary and never flips. We simply run that same clean logic twice and subtract:

  • Count all groups with at most 2 spectacle students → A
  • Count all groups with at most 1 spectacle student → B
  • Answer = A − B

When you subtract, the groups with 0 and 1 spectacle students cancel out from both sides, and what remains is exactly the groups with 2. The exact answer falls out cleanly without ever chasing “exactly 2” directly.
In code, we write mostly:
answer = count_at_most(arr, k) − count_at_most(arr, k − 1)

Exactly == k variant[AI Generated]

Practice Problems:

  • Count Number of Nice Subarrays
  • Binary Subarrays With Sum
  • Subarrays with K Different Integers
  • Count Vowel Substrings of a String
  • Number of Substrings Containing All Three Characters

Note: Any time a problem says “count subarrays where something equals exactly k”, think of this variant and reach for the subtraction trick.

Variant 4 — Shortest or Minimum Window :
So far we have been either maximizing the window or counting windows. This variant flips the goal here you want the smallest possible window that still satisfies a condition.
Imagine you are checking attendance in a long row of students and you need to find the smallest consecutive group that includes at least one girl, one boy, and the class leader. You start from the left and keep adding students expanding the window to the right until all three are present. The moment your condition is met, instead of expanding further, you do the opposite.

You start removing students from the left, one by one, and check if the condition still holds. Each time you successfully remove someone and the group still has all three, you record that smaller size. The moment removing one more would break the condition, you stop shrinking and go back to expanding from the right. You repeat this across the entire row.
This is the key difference from Variant 2. In Variant 2 you shrink when the condition breaks to fix the window. Here you shrink when the condition is met to minimize the window. Same two pointers, opposite trigger.

Minimum Window [AI Generated]

Practice Problems:

  • Minimum Window Substring
  • Minimum Size Subarray Sum
  • Minimum Operations to Reduce X to Zero
  • Longest Subarray of 1s After Deleting One Element
  • Maximum Length of Repeated Subarray

Note: Any time a problem says “find the smallest subarray or substring that satisfies a condition”, this is your variant.

I mainly explained how the Sliding Window technique works and the intuition behind each variant. If you practice the problems I mentioned, you will slowly get a strong grip on every variant and understand how to solve them. Most problems can be solved using these patterns, but depending on the question, you may need to use other data structures or slightly transform the problem into one of these variants. I did not focus much on coding in this post and in my previous Two Pointers journal because I feel that once your intuition becomes strong and you practice enough problems, coding the solution becomes much easier. My main goal here is to help you develop the thinking process behind these patterns.

Lets get into when we should apply the Sliding Window technique. The first thing I am not going to say is to simply remember a few keywords and directly apply sliding window. Mainly, you should pick the problem, try solving it, observe the common patterns you find, and think about why this pattern is being applied. By doing this, you will slowly build intuition. This intuition improves as you solve more and more problems. As of now, I will give some rules that help us identify when Sliding Window can be applied.

1.Same Order:
The order of the elements should not change because, in sliding window, we generally remove elements from the left pointer and add elements from the right pointer as the window moves. If the order changes, the result may also change, and the whole idea of reusing the previous window breaks. So, the original order must remain the same.

2. Contiguous Range Requirement:
If we pick a window between L and R, then all elements between them must be included. We cannot skip elements in between. That is why sliding window is mostly used for subarray or substring problems and not for subset problems.
3. Monotonic Property :
This is what most people miss. Here, monotonicity means the condition should move in one predictable direction. It should not randomly flip between valid and invalid while adding or removing elements.
What monotonicity means is:

  • If a window [L, R] is valid and you expand to the right, it either stays valid or becomes invalid.
  • If a window [L, R] is invalid and you shrink from the left, it either becomes valid or stays invalid.
Identifying Sliding Window problems [AI Generated]

Before we wrap up, let me show you where this pattern quietly shows up in AI/ML.

From Sliding Window to Attention: The ML Connection:

The attention mechanism used in modern AI can be understood as a smarter version of the sliding window idea. In a sliding window, we move through a sequence step by step while looking at a relevant range of previous elements instead of processing everything from scratch again and again.

Transformers process text in a very similar way. When the model reads a sentence, it breaks it into tokens and processes them all at once, but for each token it looks back at the surrounding context to understand meaning. So while reading a sentence, the model is constantly moving through the sequence and using past context which is very similar to how a sliding window moves through an array. But there is one major difference. In a normal sliding window, every element inside the window is treated equally. But in real language, not every word is equally important.

For example, in the sentence: “The cat sat on the mat”

If we want to understand the word “mat”, the word “on” is much more useful than the word “the”. A regular sliding window would give both words the same importance. Attention fixes this by learning which words matter more and giving them higher weights.

So attention keeps the same sliding window idea looking back at previous words while moving through the sequence but instead of equal weights, it gives higher weight to more relevant words and lower weight to less important ones. The image below gives some intuition about how this works.

Attention as a learned sliding window: a regular sliding window gives every word an equal weight of 1/5, but attention computes a similarity score between each word and the target word “mat”, then assigns weights based on relevance. “on” gets 65% weight because it carries the most meaning in context. “the” gets only 5%. Same window idea — but the weights are now learned, not assumed.

The window still moves forward token by token. The only difference is that the model now knows where to focus giving more weight to what matters and less to what does not. In fact, modern models run multiple attention heads in parallel, each one focusing on a different aspect of meaning, and combine all the results together. This is called multi-head attention. This single idea is the foundation of every major AI model built today like BERT, GPT, and everything after them.

What’s coming next: In the next article, I will write about the Binary Search and once again try connecting the dots with some real AI/ML applications. Until then, open LeetCode, search “Sliding Window,” and solve a few problems.

I wrote this article to organize everything I learned about the Sliding Window pattern in one place and to explain it in the way I wish I had learned it earlier. If this helps you understand the pattern a little faster or makes even one problem click for you, then this article has done its job. Thank you for reading. If you notice any mistakes, gaps, or better ways to think about the pattern, feel free to share them I am always open to learning.

— An


Pattern 2: Sliding Window Technique was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top