const solve = (nums) => { let left = 0, right = nums.length - 1; while (left < right) { const sum = nums[left] + nums[right]; if (sum === target) return [left, right]; }}
Patterns

Sliding Window LeetCode Pattern: The Complete Deep Dive

Sliding window turns O(n^2) brute force into O(n) elegance — master both fixed and variable window variants with a single reusable template that solves 15+ interview problems.

10 min read|

Sliding window turns O(n^2) brute force into O(n) elegance

Fixed and variable window templates that solve 15+ interview problems

Sliding Window Turns Brute Force Into Elegance

If you have ever written a nested loop to check every subarray of an array or every substring of a string, you have already encountered the problem that the sliding window technique was invented to solve. That O(n^2) brute force approach recalculates overlapping work on every iteration — and the sliding window pattern eliminates that redundancy by maintaining a running window of elements that expands and contracts as it moves through the input.

The sliding window leetcode pattern is one of the highest-ROI patterns you can master for coding interviews. It appears in at least 15 commonly asked problems across easy, medium, and hard difficulty levels, and once you internalize the template, new sliding window problems become almost mechanical to solve. Companies like Google, Meta, Amazon, and Microsoft all test this pattern regularly.

This deep dive covers everything you need: the two core variants (fixed-size and variable-size), the universal template that handles both, walkthroughs of five classic problems, and the boundary conditions where sliding window breaks down. By the end, you will have a mental framework that makes these problems feel like fill-in-the-blanks rather than fresh puzzles.

What Is the Sliding Window Technique?

A sliding window is a conceptual window — defined by two pointers, usually called left and right — that moves across a sequence (array or string) to examine contiguous subarrays or substrings. Instead of recalculating everything from scratch for each position, you update the window state incrementally: add the new element entering on the right, remove the old element leaving on the left, and check your condition.

There are two fundamental variants. A fixed-size sliding window has a predetermined width K — you expand until the window reaches size K, then slide it one position at a time. A variable-size sliding window expands and contracts dynamically based on a condition — you grow the right side until a constraint is violated, then shrink the left side until the constraint is satisfied again.

The key recognition trigger for sliding window problems is the phrase "contiguous subarray" or "substring." If a problem asks you to find the longest, shortest, or maximum/minimum something within a contiguous range, sliding window should be your first instinct. This pattern works because the window condition is monotonic — expanding the window can only make it "more" of something (longer, larger sum, more characters), and shrinking can only make it "less."

  • Fixed-size window: window width is given (e.g., "subarray of size K")
  • Variable-size window: window width changes based on a condition (e.g., "longest substring where...")
  • Recognition trigger: "contiguous subarray" or "substring" in the problem statement
  • Core advantage: O(n) time instead of O(n^2) by avoiding redundant recalculation
ℹ️

Key Recognition Trigger

Sliding window problems always involve contiguous subarrays or substrings — if the problem asks about subsequences (non-contiguous), sliding window won't work. This is the key recognition trigger.

Fixed-Size Sliding Window Problems

The fixed-size sliding window is the simpler of the two variants and the best place to start learning the pattern. The window has a predetermined size K, and you slide it across the array one element at a time. At each position, you add the incoming element on the right and remove the outgoing element on the left, then update your answer.

The classic example is Maximum Sum Subarray of Size K. Given an array of integers and a number K, find the maximum sum of any contiguous subarray of size K. The brute force approach recalculates the sum for every window position in O(n*K) time. With a sliding window, you compute the first window sum, then for each subsequent position you add the new right element and subtract the old left element — O(n) total.

Another common fixed-size problem is the Moving Average from Data Stream (LeetCode #346). You maintain a queue of the last K elements and update the running sum as new elements arrive. The fixed-size template is straightforward: initialize, expand to size K, then slide.

  1. 1Initialize your window state (sum, count, hash map, etc.) to empty
  2. 2Expand the right pointer from 0 to K-1, adding each element to the window state
  3. 3Record the answer for the first complete window
  4. 4For each new right position from K to n-1: add the right element, remove the left element (at right - K), update the answer
  5. 5Return the best answer found across all window positions

Variable-Size Sliding Window: The Harder Variant

The variable-size sliding window is where the pattern gets powerful — and where most interview problems live. Instead of a fixed width, you expand the right pointer one step at a time, and after each expansion, you check whether the current window violates a constraint. If it does, you shrink from the left until the constraint is satisfied again. The answer is updated either during expansion or after shrinking, depending on the problem.

The variable size sliding window works because the condition has a monotonic property. If a window of size W satisfies the constraint, then a smaller window within it might also satisfy it (or might not — that is what shrinking checks). And if a window violates the constraint, making it larger will not fix the violation. This monotonicity is what allows the two-pointer approach to work without missing any valid windows.

Consider the problem Minimum Size Subarray Sum (LeetCode #209): find the smallest contiguous subarray whose sum is greater than or equal to a target. You expand right to grow the sum. Once the sum meets the target, you try shrinking from the left to find the smallest valid window. Each element is added once and removed at most once, giving O(n) time — a dramatic improvement over checking all O(n^2) subarrays.

The key insight is that both pointers only move forward. The right pointer never moves backward, and neither does the left pointer. This means each element is visited at most twice (once by right, once by left), guaranteeing O(n) time complexity regardless of the input.

💡

Pro Tip

The universal sliding window template has 4 steps: expand right, update window state, while condition violated shrink left, update answer. Memorize this skeleton and every sliding window problem becomes fill-in-the-blanks.

Classic Sliding Window LeetCode Problems

Five problems form the core canon of sliding window leetcode questions. Mastering these gives you the pattern recognition to handle virtually any sliding window variant you encounter in an interview.

Longest Substring Without Repeating Characters (LeetCode #3) is the most frequently asked sliding window problem. You maintain a hash set of characters in the current window. Expand right — if the new character is already in the set, shrink left until it is removed. Track the maximum window length. This is the textbook variable-size window with a "no duplicates" constraint.

Minimum Window Substring (LeetCode #76) asks for the smallest window in string S that contains all characters of string T. You use two frequency maps — one for T and one for the current window. Expand right to include characters, shrink left when all of T is covered. This is the hardest common sliding window problem because the constraint involves matching character frequencies, not just membership.

Longest Repeating Character Replacement (LeetCode #424) allows you to replace at most K characters in a substring to make all characters the same. The window is valid when window_length - count_of_most_frequent_char <= K. Expand right, track character frequencies, shrink left when the condition breaks. This problem teaches you that the window state can be a frequency map with a derived condition.

Permutation in String (LeetCode #567) checks whether any permutation of string S1 exists as a substring in S2. This is a fixed-size window of length S1, sliding across S2, comparing character frequency maps at each position. It bridges fixed and variable window concepts.

Sliding Window Maximum (LeetCode #239) finds the maximum in every window of size K. This uses a monotonic deque rather than a simple hash map, making it a fixed-size window with an advanced data structure. It is rated hard and tests whether you can combine the sliding window template with a monotonic deque.

  • LeetCode #3 — Longest Substring Without Repeating Characters (Medium): hash set + variable window
  • LeetCode #76 — Minimum Window Substring (Hard): frequency map + variable window
  • LeetCode #424 — Longest Repeating Character Replacement (Medium): frequency map + derived condition
  • LeetCode #567 — Permutation in String (Medium): fixed window + frequency comparison
  • LeetCode #239 — Sliding Window Maximum (Hard): fixed window + monotonic deque

The Universal Sliding Window Template

Every sliding window problem follows the same four-step skeleton. Once you memorize this template, solving a new sliding window problem becomes a matter of filling in the blanks for your specific constraint and window state. Here is the universal sliding window template in pseudocode form.

Step one: initialize two pointers (left = 0, right = 0) and your window state (hash map, counter, sum, or whatever the problem requires). Step two: expand the window by moving right forward and updating the window state with the new element. Step three: while the window violates the constraint, shrink by removing the left element from the window state and incrementing left. Step four: update your answer (maximum length, minimum length, count, etc.) — depending on the problem, this happens either after expanding or after shrinking.

For fixed-size windows, step three is simplified: instead of a while loop checking a condition, you simply check if the window size exceeds K and remove the left element if so. The rest of the template stays identical. This is why learning the variable-size version first actually makes the fixed-size version trivial — it is just a special case.

The window state is the part that changes between problems. For substring problems, it is usually a hash map of character frequencies. For subarray sum problems, it is a running sum. For "at most K distinct" problems, it is a hash map tracking the count of distinct elements. Identify the state, plug it into the template, and the solution writes itself.

  1. 1Initialize: left = 0, window_state = empty (hash map, sum, counter, etc.)
  2. 2Expand: for right in range(n): add input[right] to window_state
  3. 3Shrink: while window_state violates constraint: remove input[left] from window_state, left += 1
  4. 4Update answer: track max/min length, count valid windows, or record the result
⚠️

Difficulty Warning

Minimum Window Substring (#76) is the hardest common sliding window problem — it combines variable-size window with a frequency map. Don't attempt it until you've solved 3-4 easier sliding window problems.

When Sliding Window Does Not Work

Sliding window is powerful, but it has clear boundaries. Knowing when the pattern does not apply is just as important as knowing when it does — it saves you from wasting ten minutes in an interview going down the wrong path.

Sliding window does not work for non-contiguous subsequences. If the problem asks about subsequences (elements that are not adjacent), you need dynamic programming or a different approach entirely. The word "subsequence" versus "subarray" or "substring" is the critical distinction in the problem statement.

The pattern also breaks down when the window condition is not monotonic. If expanding the window can both satisfy and violate the constraint depending on the specific elements, the two-pointer approach cannot guarantee correctness. For example, if the array contains negative numbers and you are looking for a subarray with a specific sum, expanding the window might decrease the sum — breaking the monotonic assumption that makes sliding window work.

Finally, some problems that look like sliding window actually require dynamic programming. The Longest Palindromic Substring (LeetCode #5) involves contiguous characters but the palindrome constraint does not have the monotonic property — a longer string is not necessarily "closer" to being a palindrome. Similarly, problems involving two separate arrays or matrices often require different approaches even if they mention windows or subarrays.

Practice identifying sliding window problems with YeetCode flashcards. The pattern recognition skill — knowing when to apply sliding window and when to reach for a different tool — is what separates candidates who solve problems in 15 minutes from those who struggle for 45.

  • Non-contiguous subsequences: use DP, not sliding window
  • Non-monotonic conditions (e.g., arrays with negatives for sum targets): consider prefix sums or hash maps
  • Palindrome problems: despite being contiguous, the constraint is not monotonic
  • Two-array or matrix problems: usually need different techniques (e.g., binary search, DP)

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now