Mastering the Sliding Window Technique

A Complete Guide with LeetCode Examples, Patterns, and Interview Tips

By Dhirendra Singh Negi


Table of Contents

  1. Introduction
  2. What is the Sliding Window Technique?
  3. Why Do We Need Sliding Windows?
  4. Brute Force Approach
  5. Fixed-Size Sliding Window
  6. Variable-Size Sliding Window
  7. How Sliding Window Works
  8. Fixed Window Problems
  9. Variable Window Problems
  10. Common Patterns
  11. Time Complexity Analysis
  12. Common Mistakes
  13. Sliding Window vs Two Pointers
  14. Interview Tips
  15. LeetCode Practice List
  16. Conclusion

Introduction

The Sliding Window technique is one of the most frequently asked coding interview topics in companies like:

  • Microsoft
  • Amazon
  • Google
  • Meta
  • Adobe
  • Walmart
  • Goldman Sachs
  • Atlassian

If you’ve solved problems like:

  • Maximum Sum Subarray
  • Longest Substring Without Repeating Characters
  • Minimum Size Subarray Sum
  • Maximum Consecutive Ones
  • Permutation in String

then you’ve already used the Sliding Window technique.

The biggest advantage is reducing an O(n²) brute-force solution into an efficient O(n) solution.


What is the Sliding Window Technique?

Imagine looking through a train window.

You only see a small portion at a time.

As the train moves, the window moves.

Similarly, in programming, instead of repeatedly examining every possible subarray or substring, we maintain a window that slides across the data.

Array

1 3 5 2 8 9 4

Window Size = 3

[1 3 5]
   ↓
  [3 5 2]
      ↓
    [5 2 8]
        ↓
      [2 8 9]

Instead of recalculating everything again, we only update what changed.


Why Do We Need Sliding Windows?

Suppose we need:

Find the maximum sum of any subarray of size 3.

Example

[2,4,1,7,8,1,2]

Window = 3

Brute Force

2+4+1
4+1+7
1+7+8
7+8+1
8+1+2

Every window requires summing again.

Time Complexity

O(n*k)

For large arrays this becomes expensive.

Sliding Window avoids repeated work.


Brute Force Approach

public int MaxSum(int[] nums, int k)
{
    int max = int.MinValue;

    for(int i = 0; i <= nums.Length - k; i++)
    {
        int sum = 0;

        for(int j = i; j < i + k; j++)
        {
            sum += nums[j];
        }

        max = Math.Max(max, sum);
    }

    return max;
}

Complexity

Time : O(n*k)

Space : O(1)


Sliding Window Optimization

Instead of recalculating,

Old Window

2 4 1

Sum = 7

Next Window

4 1 7

Remove 2
Add 7

New Sum = 12

Only two operations.


Fixed-Size Sliding Window

This window size never changes.

Example

Find maximum sum of size K

Algorithm

1. Calculate first window
2. Remove left element
3. Add right element
4. Update answer


Example

Array

2 4 1 7 8 1 2

Window Size = 3

[2 4 1] =7

[4 1 7]=12

[1 7 8]=16

[7 8 1]=16

[8 1 2]=11

Answer

16


C# Solution

public int MaxSum(int[] nums, int k)
{
    int sum = 0;

    for(int i=0;i<k;i++)
        sum += nums[i];

    int max = sum;

    for(int i=k;i<nums.Length;i++)
    {
        sum += nums[i];
        sum -= nums[i-k];

        max = Math.Max(max,sum);
    }

    return max;
}

Complexity

Time  O(n)

Space O(1)


Variable-Size Sliding Window

Here, the window grows and shrinks based on a condition.

Example

Longest substring without repeating characters

or

Minimum subarray with sum ≥ target

Window

Expand →

Shrink ←

Both pointers move only forward.


General Template

int left = 0;

for(int right = 0; right < nums.Length; right++)
{
    // Expand window

    while(condition)
    {
        // Shrink window

        left++;
    }

    // Update answer
}


Example 1

Minimum Size Subarray Sum

LeetCode 209

Given

target = 7

nums =

2 3 1 2 4 3

Visualization

2

2 3

2 3 1

2 3 1 2

Sum=8

Shrink

3 1 2

Sum=6

Expand

3 1 2 4

Sum=10

Shrink

Eventually answer

2

[4,3]


C# Solution

public int MinSubArrayLen(int target, int[] nums)
{
    int left = 0;
    int sum = 0;
    int answer = int.MaxValue;

    for(int right = 0; right < nums.Length; right++)
    {
        sum += nums[right];

        while(sum >= target)
        {
            answer = Math.Min(answer, right - left + 1);

            sum -= nums[left];
            left++;
        }
    }

    return answer == int.MaxValue ? 0 : answer;
}

Complexity

Time O(n)

Space O(1)


Example 2

Longest Substring Without Repeating Characters

LeetCode 3

Input

abcabcbb

Window

abc

abca

Duplicate

Remove left

bca

Continue

Solution

public int LengthOfLongestSubstring(string s)
{
    var set = new HashSet<char>();

    int left = 0;
    int max = 0;

    for(int right = 0; right < s.Length; right++)
    {
        while(set.Contains(s[right]))
        {
            set.Remove(s[left]);
            left++;
        }

        set.Add(s[right]);

        max = Math.Max(max, right-left+1);
    }

    return max;
}

Complexity

Time O(n)

Space O(128)


Example 3

Maximum Average Subarray I

LeetCode 643

Find the maximum average of any subarray of size k.

public double FindMaxAverage(int[] nums, int k)
{
    int sum = 0;

    for (int i = 0; i < k; i++)
        sum += nums[i];

    int max = sum;

    for (int i = k; i < nums.Length; i++)
    {
        sum += nums[i] - nums[i - k];
        max = Math.Max(max, sum);
    }

    return (double)max / k;
}


When Should You Use Sliding Window?

Sliding Window is a strong candidate when a problem mentions:

  • Subarray
  • Substring
  • Continuous elements
  • Contiguous sequence
  • Fixed window size
  • Longest or shortest contiguous range
  • Maximum or minimum value in a contiguous range
  • At most K distinct elements
  • Exactly K distinct elements
  • Sum greater than or equal to a target

If the elements do not need to be contiguous, Sliding Window is usually not the right approach.


Common Sliding Window Patterns

PatternExample Problem
Fixed-size windowMaximum Sum Subarray
Variable-size windowMinimum Size Subarray Sum
Longest valid windowLongest Repeating Character Replacement
Shortest valid windowMinimum Window Substring
Frequency countingPermutation in String
Distinct elementsLongest Substring with K Distinct Characters
Running averageMaximum Average Subarray
Binary arrayMax Consecutive Ones III

Sliding Window vs Two Pointers

Sliding WindowTwo Pointers
Maintains a continuous windowPointers may move independently
Best for subarrays/substringsBest for sorted arrays, linked lists, partitions
Often keeps a running sum or frequency mapOften compares values from both ends
Expands and shrinks a rangeMoves pointers to satisfy a condition

Think of Sliding Window as a specialized application of the Two Pointers technique where the pointers define a contiguous range.


Common Mistakes

1. Forgetting to remove the left element

sum -= nums[left];
left++;


2. Incorrect window length

Correct:

right - left + 1

Incorrect:

right - left


3. Using if instead of while

If multiple elements must be removed before the window becomes valid, use:

while(condition)
{
    ...
}

instead of:

if(condition)
{
    ...
}


4. Recomputing the entire window

Avoid recalculating sums or frequencies from scratch. Update them incrementally as the window moves.


Time Complexity

OperationComplexity
Fixed Sliding WindowO(n)
Variable Sliding WindowO(n)
Space (sum only)O(1)
Space (HashMap/HashSet)O(k)

Even though there may be nested while loops, each element enters and leaves the window at most once, making the total work linear.


Interview Tips

During interviews:

  1. Determine whether the problem requires contiguous elements.
  2. Ask whether the window size is fixed or variable.
  3. Decide what state needs to be maintained (sum, count, frequency map, etc.).
  4. Explain how the window expands and when it should shrink.
  5. Discuss the time complexity improvement from brute force to Sliding Window.

Interviewers often value your reasoning as much as the final implementation.


Must-Solve LeetCode Problems

Easy

    1. Maximum Average Subarray I
    1. Maximum Number of Vowels in a Substring of Given Length
    1. Contains Duplicate II

Medium

    1. Longest Substring Without Repeating Characters
    1. Minimum Size Subarray Sum
    1. Longest Repeating Character Replacement
    1. Permutation in String
    1. Fruit Into Baskets
    1. Max Consecutive Ones III
    1. Find All Anagrams in a String
    1. Binary Subarrays With Sum

Hard

    1. Minimum Window Substring
    1. Sliding Window Maximum
    1. Subarrays with K Different Integers

Key Takeaways

  • Sliding Window transforms many O(n²) solutions into O(n).
  • It is ideal for problems involving contiguous subarrays and substrings.
  • There are two primary variants: Fixed-Size and Variable-Size windows.
  • The technique often relies on maintaining incremental state such as sums, counts, or frequency maps.
  • Mastering Sliding Window will help you solve a large class of interview problems efficiently.

Conclusion

The Sliding Window technique is one of the highest-impact algorithms to learn for coding interviews. It builds on the idea of maintaining a moving range instead of repeatedly recalculating results, making solutions both elegant and efficient.

A good learning progression is:

  1. Master fixed-size windows.
  2. Learn variable-size windows with sums.
  3. Practice windows using HashSet and Dictionary.
  4. Solve advanced problems involving frequency maps and multiple constraints.
  5. Move on to harder variants like Minimum Window Substring and Sliding Window Maximum.

Once you’re comfortable recognizing sliding window patterns, many seemingly difficult array and string problems become straightforward to solve.

Leave a Comment