DSA
Master Sliding Window: 4 templates for Coding Interviews
Master 4 sliding window techniques used in Google, Amazon, and Meta interviews. Learn patterns with 30 curated problems, AI-powered hints, and instant feedback.

You've spent hours grinding LeetCode. You know the brute force for "Longest Substring Without Repeating Characters," but every time the interviewer tweaks the question—asks for the longest subarray with a sum under k, or the minimum window containing all characters—you freeze. All those solutions you memorized? Suddenly, they're foggy.
Sound familiar? You’re not alone. Most engineers can recall a solution, but struggle to generalize when the problem’s details shift. You keep thinking, “I’ve seen something like this before… but what’s the trick this time?”
Here’s the truth: Success in FAANG interviews isn’t about memorizing 500 solutions—it’s about recognizing the patterns behind those solutions. And if there’s one pattern that unlocks dozens of “hard” string and array questions, it’s the Sliding Window. Mastering it means you’ll spend less time panicking and more time solving.
What You'll Learn
By the end of this guide, you'll master:
✅ The 4 Sliding Window sub-patterns—character frequency matching, fixed-size, monotonic queue, and variable-size templates
✅ Pattern recognition skills so you can spot sliding window problems instantly
✅ 30 curated practice problems from Google, Amazon, Facebook, Microsoft, and more
✅ When to use each sub-pattern and how to pick the right one in an interview
✅ Common pitfalls (and how to avoid them) that trip up even experienced devs
✅ A practice roadmap to go from beginner to interview-ready in 2-3 weeks
What is Sliding Window?
Imagine looking through a moving train window: you see a section of the landscape at any moment, and as the train moves, your view shifts—revealing new features while others disappear behind you. This is the Sliding Window pattern: you examine a “window” (usually a subarray or substring) that moves step-by-step across your data, efficiently capturing only what you need at each step.
The core insight: Instead of re-processing the entire window every time, you incrementally update your answer by only considering what enters and leaves the window as you slide it. This transforms brute force O(n²) solutions into elegant O(n) ones.
Why This Pattern Matters
Sliding window is a must-have tool in your interview toolbox because it:
- Turns brute force into optimal: Shrinks O(n²) solutions to O(n), a must for large inputs.
- Appears everywhere: Over 20% of FAANG array and string questions are sliding window variants.
- Tests real-world engineering skills: It’s about state management, not blind iteration—much like writing efficient production code.
- Unlocks advanced patterns: Mastering sliding window helps you with two-pointer, prefix sum, and even dynamic programming problems like those covered in Master Dynamic Programming (DP) Patterns: 12 templates for Coding Interviews.
Companies that frequently ask sliding window questions: Google, Amazon, Meta (Facebook), Microsoft, Apple, Bloomberg, ByteDance, Uber, Lyft.
The 4 Sliding Window Sub-Patterns
Let’s break down the sliding window into 4 powerful sub-patterns. Each one has its own “template” and problem flavor—nail these, and you’ll decode almost any windowed question.
1. Character Frequency Matching
What it is
Character Frequency Matching uses a window (usually over a string) to maintain the count of each character, comparing it to some target frequency. Think: finding all substrings that are anagrams, or checking if a permutation exists.
Key insight
Rather than recomputing the entire frequency map for each substring (O(nk)), you update the counts as the window slides: add the new character, remove the old one. Compare only when needed.
How it works
- Build a frequency map for the target string (e.g., the anagram you want to match).
- Use a second map to track frequencies in the current window.
- Slide the window over the source string, updating the counts as characters enter/leave.
- Compare the maps (or a match count) to check for matches efficiently.
When to use
- When you need to check for substrings that are permutations or anagrams of a pattern.
- When the problem asks for all matching substrings of fixed length.
- When you must count or locate all windows with specific character counts.
- When working with character sets (a–z, A–Z, 0–9) where map-based counting is feasible.
Recognition triggers
- “Find all anagrams” or “permutations in a string.”
- “Window of length k,” “substring of size N.”
- “Count frequency of each character/element.”
- “Check if substring matches pattern.”
Essential Problems
Medium:
- ⭐ Permutation in String - Facebook, Microsoft, Adobe, Amazon, Yandex
Given two strings, check if one is a permutation of a substring of the other (classic frequency matching). - ⭐ Find All Anagrams in a String - Facebook, Amazon, Bloomberg, Microsoft, Snapchat
Find all start indices of anagrams of a pattern within a larger string. This is the “hello world” of frequency-matching windows.
💡 Pro Tip
When your alphabet is small (such as lowercase a–z), use fixed-length arrays instead of hash maps for frequency counts—this saves both time and space. Use a “matches” counter to avoid comparing the entire map each time.
⚠️ Common Mistake
Many engineers forget to update the outgoing character when the window slides, leading to incorrect frequency maps and false matches. Always decrement the count for the character that leaves the window!
Example Code Pattern
PYTHON
O(n) time, O(1) space for fixed alphabets; O(n) space for arbitrary character sets.
2. Fixed Size (Subarray Calculation)
What it is
Fixed Size Sliding Window calculates a property (sum, mean, max, etc.) over all subarrays/substrings of a given fixed length, efficiently updating the result as the window slides.
Key insight
You don’t need to recompute the entire sum (or other property) for each window. Instead, subtract the outgoing element and add the incoming one as the window slides—keeping your computation O(1) per step.
How it works
- Initialize the window by computing the sum (or relevant statistic) for the first k elements.
- Slide the window forward one element at a time:
- Subtract the element leaving the window.
- Add the new element entering the window.
- Update your answer as needed (e.g., track the max mean, or keep a list of all window sums).
When to use
- When the window size k is fixed and known.
- When you must find the max/min/average/sum for all subarrays of size k.
- When the window property can be updated incrementally.
- When the problem asks for “every subarray of length k.”
Recognition triggers
- “Find the max/min/average/sum of all k-length subarrays.”
- “Moving average.”
- “Fixed window of size k.”
- “For every window of length k…”
Essential Problems
Easy:
- ⭐ Maximum Average Subarray I - Amazon
Find the contiguous subarray of length k with the maximum average—a classic fixed window starter. - Calculate Compressed Mean - Google, Amazon, Facebook, Microsoft
Efficiently compute a moving mean over a data stream. - Find X-Sum of All K-Long Subarrays I
- Moving Average from Data Stream - Google, Apple, Spotify, Indeed, Amazon
Implement a real-time moving average calculator for a data stream.
Medium:
💡 Pro Tip
For moving averages or sums, keep a running sum variable and update it in O(1) as the window slides. You only need to store k values if the problem requires reconstructing the window, otherwise, just the sum and a count suffice.
⚠️ Common Mistake
Starting the window at the wrong index (off-by-one errors) or failing to handle the initialization (the first window) properly. Always ensure your initial window is fully populated before sliding.
Example Code Pattern
PYTHON
O(n) time, O(1) space.
3. Monotonic Queue for Max/Min
What it is
Monotonic Queue Sliding Window is a specialized pattern for maintaining the max or min in a sliding window, using a double-ended queue (deque) to keep potential maximums/minimums in monotonic (increasing or decreasing) order.
Key insight
Instead of scanning the window for the max/min at each step (O(k)), you maintain a deque where the front always holds the current max/min. As new elements come in:
- Remove elements from the back that can never be the max/min again.
- Remove the front if it’s outside the window.
- This keeps each element added and removed at most once—O(n) total.
How it works
- For each new element:
- Pop from the back of the deque while the new element is larger (for max) or smaller (for min).
- Add the new element’s index to the deque.
- Remove the front if it’s outside the window.
- The current max/min is always at the front.
When to use
- When you need the max/min of every sliding window of size k, not just one window.
- When the brute force is O(nk) and k can be large.
- When “window maximum/minimum” is a keyword.
- When asked for “shortest/longest subarray with some property” and efficient max/min tracking is required.
Recognition triggers
- “Sliding window maximum/minimum.”
- “Find the maximum/minimum in every window of size k.”
- “Shortest/longest subarray with constraints.”
- “Efficiently maintain max/min as window slides.”
Essential Problems
Medium:
- ⭐ Jump Game VI - Uber
Dynamic programming with a sliding window max—classic for monotonic queue.
Hard:
- ⭐ Sliding Window Maximum - Amazon, ByteDance, Dropbox, Facebook, Google
Find the max in every window—textbook monotonic queue. - Shortest Subarray with Sum at Least K - Goldman Sachs
💡 Pro Tip
Practice deque operations so you’re comfortable with collections.deque in Python. In interviews, verbalize why you remove from the deque’s back/front—it shows you understand the invariant.
⚠️ Common Mistake
Forgetting to remove elements from the front of the queue that are outside the current window, leading to stale results. Always check window boundaries before using the deque’s front.
Example Code Pattern
PYTHON
O(n) time, O(k) space.
4. Variable Size (Condition-Based) Sliding Window
What it is
Variable Size Sliding Window dynamically expands or contracts based on conditions—such as sum, product, unique elements, or other constraints. The window size isn’t fixed; it grows or shrinks to satisfy the required property.
Key insight
You greedily expand the window (move the right pointer) to include more elements, and contract it (move the left pointer) when the constraint is violated. You only process each element as it enters and exits the window—O(n) time.
How it works
- Initialize left and right pointers at start.
- Expand right pointer to include elements until the constraint is violated.
- While invalid, increment left pointer to shrink the window until constraint is satisfied.
- Update the answer (max/min length, count, etc.) as appropriate.
When to use
- When the window size is not fixed and depends on a sum, product, unique elements, or other dynamic conditions.
- When asked for “longest/shortest subarray/substring with at most/at least X.”
- When you need to count the number of valid subarrays meeting a constraint.
- Problems involving adjustable window size based on state.
Recognition triggers
- “At most/at least k unique elements/characters.”
- “Longest/shortest subarray/substring with property X.”
- “Shrink window until condition is met.”
- “Count subarrays/strings that satisfy a constraint.”
Essential Problems
Easy:
- ⭐ Contains Duplicate II - Facebook, Amazon
Find if any duplicates exist within k distance—a gentle intro to condition-based windows.
Medium:
- ⭐ Longest Substring Without Repeating Characters - Amazon, Bloomberg, Microsoft, Facebook, Apple
Classic: find the max-length substring with no repeats. Master this—variations abound! - ⭐ Minimum Size Subarray Sum - Goldman Sachs, Amazon, Bloomberg, Facebook, Microsoft
Find the shortest subarray with sum at least s. Perfect for learning window contraction. - Subarray Product Less Than K - Bloomberg, LinkedIn
- Max Consecutive Ones III - Facebook, Coupang, HBO
- Maximum Frequency of an Element After Performing Operations I
- Maximum Good Subarray Sum
- Maximum Beauty of an Array After Applying Operation
- Continuous Subarrays
- Maximum Sum of Distinct Subarrays With Length K
- Take K of Each Character From Left and Right
- Longest Repeating Character Replacement - Google, Amazon, Wish
- Longest Subarray of 1's After Deleting One Element - Yandex
- Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit - Google
- Minimum Operations to Reduce X to Zero - Google
- Fruit Into Baskets - Google, Akamai
- Find Longest Special Substring That Occurs Thrice I
- Frequency of the Most Frequent Element
Hard:
- ⭐ Minimum Window Substring - Facebook, Amazon, Microsoft, Lyft, Apple
Find the smallest window containing all characters of a pattern—a gold standard interview problem. - Maximum Frequency of an Element After Performing Operations II
💡 Pro Tip
Explicitly track the state your window must satisfy (sum, unique count, etc.). Use hash maps or counters for elements as needed. In interviews, speak out loud about when and why you shrink or expand the window.
⚠️ Common Mistake
Not shrinking or expanding the window correctly when the constraint is violated, leading to incorrect window sizes or missing results. Double-check your left/right pointer movement logic—draw it out if needed!
Example Code Pattern
PYTHON
O(n) time, O(k) space where k is charset size.
How to Master Sliding Window on Thita.ai
Ready to go from theory to interview-ready? Here’s how Thita.ai supercharges your sliding window mastery:
- Pattern-Based Problem Sets: Tackle hand-picked sliding window sets at DSA Patterns Sheet for focused practice.
- AI Hints & Instant Feedback: Stuck? Get AI-powered guidance and code reviews as you solve at Best Ways to Use AI for DSA and Coding Interview Preparation, which covers how to leverage AI coding interview tools effectively.
- Real Interview Simulation: Practice full-length, FAANG-style interviews with live feedback at AI Interview.
- Track Your Progress: Visualize your strengths, weaknesses, and streaks at Dashboard.
- Technical Coaching: Book a session with an AI Coach for 1:1 feedback and pattern deep dives at AI Coach.
Your Sliding Window Learning Roadmap
Master all 4 sub-patterns in just 2–3 weeks, with a clear daily plan:
Week 1: Foundations (Easy & Core Concepts)
Day 1:
- Maximum Average Subarray I (Amazon)
- Moving Average from Data Stream (Google, Apple, Spotify, Indeed, Amazon)
Goal: Grasp fixed-size template and running sum.
Day 2:
- Contains Duplicate II (Facebook, Amazon)
- Calculate Compressed Mean (Google, Amazon, Facebook, Microsoft)
Goal: Practice basic sliding window detection and frequency patterns.
Day 3-4:
- Find X-Sum of All K-Long Subarrays I
- Find the Power of K-Size Subarrays I
- Review all Easy problems and re-solve any you missed.
Time: 60-90 minutes per day.
Week 2: Intermediate (Medium Problems & Subpatterns)
Day 5-6: Character Frequency Matching & Fixed Size
- Permutation in String (Facebook, Microsoft, Adobe, Amazon, Yandex) ⭐
- Find All Anagrams in a String (Facebook, Amazon, Bloomberg, Microsoft, Snapchat) ⭐
- Maximum Frequency of an Element After Performing Operations I
Day 7-8: Variable Size (Condition-Based)
- Longest Substring Without Repeating Characters (Amazon, Bloomberg, Microsoft, Facebook, Apple) ⭐
- Minimum Size Subarray Sum (Goldman Sachs, Amazon, Bloomberg, Facebook, Microsoft) ⭐
- Max Consecutive Ones III (Facebook, Coupang, HBO)
- Subarray Product Less Than K (Bloomberg, LinkedIn)
Day 9: Monotonic Queue for Max/Min
- Jump Game VI (Uber) ⭐
- Continuous Subarrays
- Maximum Sum of Distinct Subarrays With Length K
Time: 90-120 minutes per day. Focus on explaining the sliding window logic aloud.
Week 3: Mastery (Hard Problems & Advanced Patterns)
Day 10-12:
- Sliding Window Maximum (Amazon, ByteDance, Dropbox, Facebook, Google) ⭐
- Shortest Subarray with Sum at Least K (Goldman Sachs)
- Minimum Window Substring (Facebook, Amazon, Microsoft, Lyft, Apple) ⭐
- Maximum Frequency of an Element After Performing Operations II
Target: Understand monotonic queue and dynamic window contraction deeply.
Day 13-14:
- Mixed challenge: Randomize 4-6 unsolved or starred Medium/Hard problems.
- Simulate a timed 60-minute interview using AI Interview with at least 2 sliding window problems.
- Review all your mistakes using Dashboard, and schedule a follow-up session with AI Coach if stuck.
Estimated time: 2 hours/day. Focus on speed, accuracy, and verbalizing your window logic.
Common Sliding Window Pitfalls
Mastery means knowing what not to do. Here are the mistakes that trip up even senior devs:
⚠️ Off-by-One Errors
Mistake: Misaligning window bounds, e.g., including or excluding the right endpoint.
Solution: Always clearly define if your window is [left, right] (inclusive) or [left, right) (right-exclusive). For example:
PYTHON
Correct:
PYTHON
⚠️ Forgetting to Update Outgoing Elements
Mistake: Not decrementing/removing the element that leaves the window, especially in frequency maps.
Solution: Always update both “add” and “remove” operations as the window slides.
⚠️ Not Handling Edge Cases (Empty/Short Inputs)
Mistake: Failing on short arrays/strings where window size exceeds input.
Solution: Add input validation and test with edge cases, e.g., empty input or k > len(array).
⚠️ Brute Forcing with Nested Loops
Mistake: Using nested loops for every window instead of incremental updates.
Solution: Identify if the window’s property can be updated in O(1) and refactor.
⚠️ Incorrect Window Contraction/Expansion
Mistake: Shrinking or expanding the window at the wrong time, missing valid subarrays or including invalid ones.
Solution: Use clear conditions and print window bounds during debugging.
⚠️ Not Using the Right Data Structure
Mistake: Using a list instead of a deque for monotonic queue problems, leading to O(n²) time.
Solution: Use collections.deque for efficient front and back operations.
⚠️ Incorrectly Comparing Frequency Maps
Mistake: Comparing entire maps each time (O(k)), missing the O(1) match counter optimization.
Solution: When possible, use a single matches variable that only updates when a character’s frequency matches or mismatches.
Why Sliding Window Beats Brute Force
Let’s see the power of sliding window with a concrete example.
Problem: Maximum Average Subarray I (Amazon)
Brute Force Approach
For every possible subarray of length k, calculate the sum and track the maximum.
PYTHON
Time Complexity: O(nk)
Space Complexity: O(1)
Sliding Window Approach
Incrementally update the sum as the window slides.
PYTHON
Time Complexity: O(n)
Space Complexity: O(1)
Key Insight:
Brute force recomputes the sum for each window, leading to repeated work. Sliding window only updates by the minimal difference (incoming minus outgoing element), slashing time complexity.
When does sliding window shine?
- When window size k is large (e.g., thousands).
- When input size is big (e.g., streaming or real-time analytics).
- When in production—latency and efficiency matter.
Beyond LeetCode: Real-World Applications
Sliding window isn’t just for interviews—it powers real-world systems at top tech companies.
1. Real-Time Analytics (Google, Facebook)
Use Case: Real-time computation of metrics (e.g., “active users in the last 5 minutes”).
How: Use fixed-size windows on event streams to calculate rolling averages or counts.
2. Intrusion Detection & Security (Amazon, Microsoft)
Use Case: Detecting login anomalies or DDoS attacks in log streams.
How: Sliding window over IP address events to find bursts or repeated access attempts within time windows.
3. Network Traffic Shaping (Netflix, Akamai)
Use Case: Maintaining bandwidth or latency guarantees.
How: Variable-size windows to enforce rate limits or detect congestion.
4. Stream Processing Frameworks (Apache Flink, Kafka Streams)
Use Case: Windowed joins, aggregations, and trend detection in big data pipelines.
How: Monotonic queues and sliding windows to keep computations efficient for billions of events.
5. Recommendation Engines (Spotify, YouTube)
Use Case: Identify trending topics, songs, or videos in the last hour/day.
How: Maintain top-N counts or unique user lists within sliding time windows.
Performance Benefits:
Sliding window enables O(1) or O(n) processing for massive data streams, where brute force would be infeasible—critical for low latency and high throughput.
Conclusion: From Memorization to Mastery
You’ve seen that sliding window isn’t just another trick—it’s a cornerstone of efficient algorithm design, both in interviews and in production code. Mastering its 4 templates means you’ll decode over 20% of FAANG string and array questions, and you’ll write cleaner, faster code.
Next steps:
- Practice all 30 sliding window problems on Thita.ai’s DSA Patterns Sheet
- Get instant AI feedback and hints as you solve at Best Ways to Use AI for DSA and Coding Interview Preparation
- Simulate real interviews and measure your progress with AI Interview
- Book a session with our AI Coach for personalized feedback at AI Coach
Remember: Pattern recognition beats memorization. The window to FAANG is open—slide through!