Apply Now Apply Now Apply Now
header_logo
Post thumbnail
DATA STRUCTURE

Sliding Window Technique: Explained with Examples

By Vishalini Devarajan

If you’ve ever solved an array or string problem using two nested loops and wondered whether there’s a smarter way, there is, and it’s called the “sliding window” technique. It’s one of the most practical and frequently tested patterns in coding interviews, and once you understand how it works, you’ll start spotting it in problems you’ve struggled with before. 

Table of contents


  1. TL;DR Summary 
  2. What Is the Sliding Window Technique?
  3. The Problem With Brute Force
  4. How the Sliding Window Works
  5. Fixed vs. Variable-Size Windows
  6. Fixed Window Example: Maximum Sum Subarray of Size K
  7. Variable Window Example: Longest Substring With K Distinct Characters
  8. Variable Window Example: Smallest Subarray With Sum ≥ Target
  9. How to Identify a Sliding Window Problem
  10. Common Sliding Window Problems to Practice
  11. When Not to Use Sliding Window
  12. Conclusion
  13. FAQs
    • When should I use a fixed-size window vs a variable-size window?
    • What’s the core update step in a sliding-window algorithm?
    • How do you keep a variable window valid?
    • Can sliding window handle negative numbers or non-monotonic conditions?
    • How do I spot sliding-window problems quickly?
    • How do you handle tracking elements efficiently inside the window?
    • What common mistakes should I avoid when coding sliding-window solutions?

TL;DR Summary 

  1. Idea: keep a window [l,r], update result by adding incoming and removing outgoing  turns many O(n²) checks into O(n).
  2. Types: fixed-size (k, shift one; e.g., max k-sum) and variable-size (expand/contract by condition; e.g., ≤k distinct, min subarray ≥ target).
  3. Pattern: two pointers + running state (sum or freq map), O(1) updates; spot contiguous-range problems (longest/shortest/max/min/count).

To learn more about the sliding window technique and how it turns nested loops into O(n) solutions. Master this and more DSA patterns in HCL GUVI’s DSA for Programmers.

What Is the Sliding Window Technique?

The sliding window technique solves subarray and substring problems by maintaining a moving range of elements, a “window,” that slides through the data one step at a time. Instead of recalculating everything from scratch at each step, it reuses the previous result, reducing time complexity from O(n²) to O(n).

The Problem With Brute Force

  • Imagine you have an array and you need to find the maximum sum of any subarray of size k. The brute-force way is to loop through every possible starting index and sum the next k elements from there. That works, but it’s O(n × k) slow when the array is large.
  • The issue is repetition. Every time you move one step forward, you’re re-summing k elements that mostly overlap with the previous window. You’re reprocessing elements you’ve already seen. The sliding window technique eliminates that redundancy.

How the Sliding Window Works

  • The core idea is simple: instead of recalculating the entire window sum from scratch, just subtract the element leaving the window and add the element entering it.
  • Here’s a concrete example. Given arr = [5, 2, -1, 0, 3] and k = 3:
  • First, compute the sum of the initial window: 5 + 2 + (-1) = 6. That’s your starting sum.
  • Now slide the window one step right. Drop 5 (the leftmost element), add 0 (the new rightmost element): 6 – 5 + 0 = 1. New window sum: 1.
  • Slide again. Drop 2, add 3: 1 – 2 + 3 = 2. New window sum: 2.
  • Track the maximum across all windows  it’s 6, from the first window [5, 2, -1].
  • Each element is visited exactly once. Time complexity: O(n). Space complexity: O(1). That’s the power of this approach.

Fixed vs. Variable-Size Windows

There are two types of sliding windows, and knowing which one to use is the key to solving different problem categories.

FeatureFixed Size WindowVariable Size Window
Window sizeSet before you start (given as k)Grows and shrinks dynamically
Pointer movementThe right pointer moves; left follows by 1The left pointer moves only when the condition breaks
Use caseMax/min sum of subarray of size kLongest/smallest subarray meeting a condition
ComplexityO(n)O(n)
Example problemsMax sum subarray of size kLongest substring with k distinct characters
  1. Fixed-size window problems give you the window size up front. You compute the first window, then slide one step at a time, adding the new element and dropping the old one.
  2. Variable-size window problems don’t give you a fixed size. You expand the right pointer when the condition holds and shrink from the left when it breaks. The window grows and contracts until you find the optimal answer.

Fixed Window Example: Maximum Sum Subarray of Size K

This is the most common entry-level sliding window problem.

Problem: Given arr = [1, 4, 2, 10, 23, 3, 1, 0, 20] and k = 4, find the maximum sum of any subarray of size 4.

Step 1: Compute the first window sum: 1 + 4 + 2 + 10 = 17. Set max_sum = 17.

Step 2: Slide the window. window_sum = 17 – 1 + 23 = 39. Update max_sum = 39.

Step 3: Slide again. window_sum = 39 – 4 + 3 = 38. max_sum stays 39.

Step 4: window_sum = 38 – 2 + 1 = 37. max_sum stays 39.

Continue until the end. The answer is 39, from the subarray [4, 2, 10, 23].

Here’s the Python code for this:

def max_sum_subarray(arr, k): n = len(arr) window_sum = sum(arr[:k]) max_sum = window_sum for i in range(n – k): window_sum = window_sum – arr[i] + arr[i + k] max_sum = max(max_sum, window_sum) return max_sum

Clean, readable, and runs in O(n). No nested loops needed.

💡 Did You Know?

The sliding window technique is highly efficient because each element is visited at most twice: once when the right pointer expands the window and once when the left pointer shrinks it. As a result, both fixed-size and variable-size sliding window algorithms run in O(n) time, even though the window size changes dynamically during execution.
MDN

Variable Window Example: Longest Substring With K Distinct Characters

This is a classic medium-difficulty problem that shows the variable window pattern.

Problem: Given string s = “araaci” and k = 2, find the length of the longest substring with at most 2 distinct characters.

  • You maintain a frequency map of characters in the current window, a left pointer, and a right pointer. Expand right at each step by adding the new character to the map.
  • When the number of distinct characters in the map exceeds k, shrink from the left, remove the leftmost character, and move left forward. Keep doing this until the window is valid again.
  • Track the maximum window length throughout. For “araaci” with k = 2, the answer is 4. The substring “araa” contains exactly 2 distinct characters: ‘a’ and ‘r’.

The logic in code:

def longest_k_distinct(s, k): left = 0 char_map = {} max_len = 0 for right in range(len(s)): char_map[s[right]] = char_map.get(s[right], 0) + 1 while len(char_map) > k: char_map[s[left]] -= 1 if char_map[s[left]] == 0: del char_map[s[left]] left += 1 max_len = max(max_len, right – left + 1) return max_len

Two pointers, one pass, O(n) time.

You explored sliding windows and how fixed/variable windows optimize array and string problems like max sum and longest substring. Build interview-ready DSA skills with HCL GUVI’s DSA for Programmers. 

Variable Window Example: Smallest Subarray With Sum ≥ Target

  • Problem: Given arr = [2, 1, 5, 2, 3, 2] and target = 7, find the length of the smallest subarray with sum ≥ 7.
  • Expand right until window_sum ≥ target. Then shrink from the left as long as the sum stays ≥ target; each valid shrink is a candidate for the minimum length. Record the smallest window length each time the condition holds.
  • For this array, the answer is 2. The subarray [5, 2] has a sum of 7 and a length of 2.
  • This is a tighter variant because you’re not just finding the longest valid window; you’re minimizing the length. The two-pointer approach handles both directions naturally.

How to Identify a Sliding Window Problem

Recognizing the pattern is more than half the work. Here are the signals to look for.

  • The problem involves a contiguous subarray or substring. The question asks for a maximum, minimum, longest, shortest, or count. The brute-force solution is obviously O(n²) with nested loops. The input involves an array, a string, or any linear sequence.
  • If you see phrases like “subarray of size k,” “longest substring with at most,” or “minimum window that satisfies,” it’s almost certainly a sliding window problem.
  • One quick test: can you represent the solution as a range [left, right] that moves through the array? If yes, the sliding window applies.

Common Sliding Window Problems to Practice

ProblemTypeKey Pattern
Max sum subarray of size kFixedAdd new, drop old
Longest substring with k distinct charsVariableExpand right, shrink left
Minimum window substringVariableShrink until invalid; track min
Longest substring without repeating charsVariableSet or map tracks seen characters.
Find all anagrams in a stringFixedCharacter frequency comparison
Maximum consecutive ones after k flipsVariableCount zeros and flip the constraint.
Subarray product less than kVariableMultiply in, divide out from the left.
Longest subarray with sum ≤ kVariableClassic two-pointer shrink

All of these reduce to the same core pattern: a window defined by two pointers, moved intelligently based on the problem’s condition.

When Not to Use Sliding Window

  • The technique only works when the problem involves contiguous elements, meaning the subarray or substring must be a connected range in the original input. If the problem involves non-contiguous subsequences (like LIS or LCS), you need dynamic programming instead.
  • Also, a sliding window assumes that adding or removing an element predictably affects the condition. Problems with complex constraints that don’t behave monotonically, where expanding the window doesn’t clearly worsen or improve the condition, may need a different approach.

Conclusion

The sliding window technique is one of those tools that, once you understand it, makes a whole category of problems feel manageable. Fixed windows are the easier starting point to learn the add-and-drop mechanic first. 

Then move to variable windows with two pointers, which unlock a much wider set of problems. The key habit to build is recognizing when a brute-force nested loop is actually just a sliding window in disguise. Practice five to ten problems across both types, and the pattern becomes second nature.

FAQs 

When should I use a fixed-size window vs a variable-size window?

Use fixed-size when k is given (e.g., subarray of size k); use variable-size when you need to meet a condition that dictates window length (e.g., ≤ k distinct chars or sum ≥ target).

What’s the core update step in a sliding-window algorithm?

Add the new element entering the window, remove the element leaving the window (or decrement its count), then update your answer (max/min/length/count) in O(1).

How do you keep a variable window valid?

Maintain a condition-driven loop: expand right to include elements, and while the condition is violated, shrink left until the window is valid again, updating the result each time it becomes valid.

Can sliding window handle negative numbers or non-monotonic conditions?

Fixed windows work fine with negatives; variable windows rely on monotonic behavior of the condition. If adding/removing elements doesn’t predictably affect the condition, sliding window may not apply.

How do I spot sliding-window problems quickly?

Look for contiguous subarray/substring requirements and asks for max/min/longest/shortest/count; if the brute-force solution uses nested loops over ranges, try reframing as a sliding window.

How do you handle tracking elements efficiently inside the window?

Use a hashmap or frequency array to count elements for strings or limited-range integers; update counts on include/exclude and remove keys when count hits zero to keep checks O(1).

MDN

What common mistakes should I avoid when coding sliding-window solutions?

Don’t place queries or updates inside inner loops, forget to handle edge cases (k > n, empty input), or fail to update left/right correctly—test with small arrays and boundary conditions.

Success Stories

Did you enjoy this article?

Schedule 1:1 free counselling

Similar Articles

Loading...
Get in Touch
Chat on Whatsapp
Request Callback
Share logo Copy link
Table of contents Table of contents
Table of contents Articles
Close button

  1. TL;DR Summary 
  2. What Is the Sliding Window Technique?
  3. The Problem With Brute Force
  4. How the Sliding Window Works
  5. Fixed vs. Variable-Size Windows
  6. Fixed Window Example: Maximum Sum Subarray of Size K
  7. Variable Window Example: Longest Substring With K Distinct Characters
  8. Variable Window Example: Smallest Subarray With Sum ≥ Target
  9. How to Identify a Sliding Window Problem
  10. Common Sliding Window Problems to Practice
  11. When Not to Use Sliding Window
  12. Conclusion
  13. FAQs
    • When should I use a fixed-size window vs a variable-size window?
    • What’s the core update step in a sliding-window algorithm?
    • How do you keep a variable window valid?
    • Can sliding window handle negative numbers or non-monotonic conditions?
    • How do I spot sliding-window problems quickly?
    • How do you handle tracking elements efficiently inside the window?
    • What common mistakes should I avoid when coding sliding-window solutions?