A Complete Guide with LeetCode Examples, Patterns, and Interview Tips
By Dhirendra Singh Negi
Table of Contents
- Introduction
- What is the Sliding Window Technique?
- Why Do We Need Sliding Windows?
- Brute Force Approach
- Fixed-Size Sliding Window
- Variable-Size Sliding Window
- How Sliding Window Works
- Fixed Window Problems
- Variable Window Problems
- Common Patterns
- Time Complexity Analysis
- Common Mistakes
- Sliding Window vs Two Pointers
- Interview Tips
- LeetCode Practice List
- Conclusion
Introduction
The Sliding Window technique is one of the most frequently asked coding interview topics in companies like:
- Microsoft
- Amazon
- 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
| Pattern | Example Problem |
|---|---|
| Fixed-size window | Maximum Sum Subarray |
| Variable-size window | Minimum Size Subarray Sum |
| Longest valid window | Longest Repeating Character Replacement |
| Shortest valid window | Minimum Window Substring |
| Frequency counting | Permutation in String |
| Distinct elements | Longest Substring with K Distinct Characters |
| Running average | Maximum Average Subarray |
| Binary array | Max Consecutive Ones III |
Sliding Window vs Two Pointers
| Sliding Window | Two Pointers |
|---|---|
| Maintains a continuous window | Pointers may move independently |
| Best for subarrays/substrings | Best for sorted arrays, linked lists, partitions |
| Often keeps a running sum or frequency map | Often compares values from both ends |
| Expands and shrinks a range | Moves 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
| Operation | Complexity |
|---|---|
| Fixed Sliding Window | O(n) |
| Variable Sliding Window | O(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:
- Determine whether the problem requires contiguous elements.
- Ask whether the window size is fixed or variable.
- Decide what state needs to be maintained (sum, count, frequency map, etc.).
- Explain how the window expands and when it should shrink.
- 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
- Maximum Average Subarray I
- Maximum Number of Vowels in a Substring of Given Length
- Contains Duplicate II
Medium
- Longest Substring Without Repeating Characters
- Minimum Size Subarray Sum
- Longest Repeating Character Replacement
- Permutation in String
- Fruit Into Baskets
- Max Consecutive Ones III
- Find All Anagrams in a String
- Binary Subarrays With Sum
Hard
- Minimum Window Substring
- Sliding Window Maximum
- 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:
- Master fixed-size windows.
- Learn variable-size windows with sums.
- Practice windows using
HashSetandDictionary. - Solve advanced problems involving frequency maps and multiple constraints.
- 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.