Introduction
The Sliding Window Technique is one of the most important concepts in DSA interviews, especially for array and string problems. Many learners struggle with this topic because they try to solve it using brute force.
In simple words, sliding window is about looking at a small part of data at a time and moving it step by step, instead of checking everything again and again.
Real-World Meaning of Sliding Window
Think of a train window:
You can see only a small portion of the outside at one time
As the train moves, the view keeps changing
You don’t look back at everything again
This is exactly how the sliding window works.
What is Sliding Window Technique?
The Sliding Window Technique is used when:
You are given an array or string
You need to find something in all subarrays or substrings of fixed size
Instead of recalculating from scratch, you:
Reuse previous results
Slide the window one step at a time
Why Brute Force is Not a Good Idea
Brute Force Approach
Check every subarray
Recalculate result every time
Problems
Too slow for large input
Time complexity becomes very high
Interviewers expect an optimized sliding window solution.
Why Deque is Used in Sliding Window Problems
Deque helps because:
We need fast insertion and deletion from both ends
We need to keep elements in a useful order
Deque allows us to maintain only useful elements inside the window.
Most Common Sliding Window Problem
Problem Statement
Given an array and a window size k, find the maximum element in every window of size k.
Example
Input: [1, 3, -1, -3, 5, 3, 6, 7]
Window Size (k): 3
Output: [3, 3, 5, 5, 6, 7]
Before vs After Understanding
Without Sliding Window
Recalculate max for every window
Too many comparisons
With Sliding Window + Deque
Keep only useful elements
Move window one step
What Interviewers Are Actually Testing
Interviewers want to see:
Can you avoid repeated work?
Do you know how to use deque smartly?
Can you think in terms of window movement?
Key Idea (Very Simple)
We store indexes in deque, not values.
The deque always stores indexes in such a way that:
Front has the maximum element index
Values are in decreasing order
Step-by-Step Logic
Create an empty deque
Loop through the array
Remove indexes from front if they are out of the window
Remove smaller elements from the back
Add current index to deque
Once window size is reached, record the front element
Dry Run Example
Array: [1, 3, -1, -3, 5, 3, 6, 7], k = 3
Join the conversation! Your thoughts help the community grow.