LogIn
I don't have account.

Sliding Window Algorithm : Beginners to Advanced Engineers

Code Crafter
24 Views

The Sliding Window technique is a powerful algorithmic approach that reduces complex problems (often solved with nested loops) into efficient linear-time solutions. It works by maintaining a "window" (a range of elements) that slides over a sequence to compute results dynamically. It allows you to process subarrays, substrings or continuous sequences on the fly. This method is a must-know for optimizing problems that deal with ranges in data.

In this article, we deep-dive into what is Sliding Window , How Sliding Window works, when to use Sliding Window, step-by-step patterns, robust code examples, real-world use cases, pitfalls, and advanced extensions so both beginners and experienced engineers gain practical value.

What is the Sliding Window Approach?

The Sliding Window technique is an efficient algorithmic strategy used to optimize problems involving sequences such as arrays, strings or linked lists. It works by :

  • Defining a window : a fixed or variable subset of elements within the sequence.
  • Sliding the window : moving it step by step across the dataset by adding a new element on one end and removing an old element from the other.
  • Reusing computations : instead of recalculating results from scratch, it updates the answer dynamically as the window moves.

Imagine it like a moving magnifying glass scanning a paragraph: instead of re-reading the whole text each time, you simply shift the glass by one word or character to continue.

Why Use the Sliding Window Technique?

  • Efficiency: Avoids recalculating values by reusing previous computations, often reducing time complexity from O(n²) to O(n).
  • Simplicity: Easier to implement compared to more complex data structures or algorithms, while still being powerful.
  • Versatility: Works well with arrays, strings, and even linked lists making it useful for subarray, substring, and continuous sequence problems.
  • Scalability: Handles large datasets efficiently, which is critical in real-world systems and production environments.

How the Sliding Window Works

The Sliding Window algorithm works by maintaining a window of elements within a sequence and adjusting it dynamically to meet problem conditions.

Step-by-step process
  • Initialize two pointers : left and right define the window boundaries.
  • Expand the window : move the right pointer forward to include new elements.
  • Shrink the window : when conditions are violated (e.g., sum too large), move the left pointer forward to restore validity.
  • Update results : track the maximum, minimum or required outcome during the process.
Example Visualization

Array: [1, 2, 3, 4, 5], Window size = 3

  • Step 1: [1, 2, 3] → sum = 6
  • Step 2: [2, 3, 4] → reuse previous sum: (6 - 1 + 4) = 9
  • Step 3: [3, 4, 5] → reuse previous sum: (9 - 2 + 5) = 12

Instead of recalculating the sum from scratch each time, we reuse previous computations, making the algorithm much more efficient.

Where to Use Sliding Window?

Sliding Window works best when you need to deal with contiguous subarrays or substrings in arrays or strings. Instead of recalculating from scratch for every subarray, you "slide" the window across and update results efficiently.

  • Fixed-Size Windows: Problems where the window length is constant, such as finding the sum, average or maximum of every subarray of size k.
  • Variable-Size Windows: When the window grows or shrinks depending on conditions, e.g., finding the longest or shortest substring that satisfies given constraints.
  • Dynamic Windows: Complex cases where conditions continuously change, requiring both expansion and contraction of the window during iteration.
  • Streaming or Real-Time Data: Useful for analytics on continuous inputs (like monitoring user activity, network packets or live sensor data).
  • Optimization Problems : When you need to maximize or minimize something in a sliding range. Eg : Longest substring with at most K distinct characters , Minimum window substring containing all characters of another string

Use Sliding Window whenever the problem involves contiguous segments (subarrays/substrings) where you need to optimize, count or validate something as the window slides.

Common Sliding Window Patterns

Identifying the right sliding window pattern is the key to transforming brute-force O(n²) solutions into elegant, efficient O(n) implementations. Below are some common sliding window patterns you’ll encounter in practice:

1. Fixed Window

A Fixed Window means the window size (k) remains constant while it slides across the array or string. You don’t expand or shrink dynamically. instead, you move the window one step at a time, adding the new element and removing the old one.

When to Use

Use a fixed window when the problem explicitly asks for operations on all subarrays/subsequences of length k. Common operations include

  • Sum-based operations : e.g., find maximum or minimum sum of subarray of size k. Real life use case : Optimizing resource allocation, bandwidth monitoring or financial trend detection.
  • Average calculations : eg., Compute the rolling average of the last k elements in time-series or streaming data. Real Life Use Case: Stock price analysis, temperature monitoring or anomaly detection in live systems.
  • Extreme value tracking : eg., Find the maximum or minimum element in every subarray of length k. Real Life Use Case: Real-time leaderboards, sliding range queries or dynamic performance monitoring.

Instead of recalculating the entire sum or aggregate every time, you reuse previous results: subtract the outgoing element, add the incoming one. This reduces computation from O(n·k) (brute force) to O(n).

Example : Find maximum or minimum sum of subarray of size k

Copy
public class SlidingWindowSum {

    public static int maxSumSubarray(int[] arr, int k) {
        if (arr.length < k) {
            throw new IllegalArgumentException("Array size must be >= k");
        }
        int windowSum = 0;
        for (int i = 0; i < k; i++) {
            windowSum += arr[i];
        }
        int maxSum = windowSum;
        for (int i = k; i < arr.length; i++) {
            windowSum += arr[i] - arr[i - k]; // remove left, add right
            maxSum = Math.max(maxSum, windowSum);
        }
        return maxSum;
    }

    public static int minSumSubarray(int[] arr, int k) {
        if (arr.length < k) {
            throw new IllegalArgumentException("Array size must be >= k");
        }
        int windowSum = 0;
        for (int i = 0; i < k; i++) {
            windowSum += arr[i];
        }
        int minSum = windowSum;
        for (int i = k; i < arr.length; i++) {
            windowSum += arr[i] - arr[i - k];
            minSum = Math.min(minSum, windowSum);
        }
        return minSum;
    }

    public static void main(String[] args) {
        int[] arr = {2, 1, 5, 1, 3, 2};
        int k = 3;
        System.out.println("Maximum sum of subarray of size " + k + ": " + maxSumSubarray(arr, k));
        // Output : Maximum sum of subarray of size 3: 9
        System.out.println("Minimum sum of subarray of size " + k + ": " + minSumSubarray(arr, k));
       // Output : Minimum sum of subarray of size 3: 6
    }
}

Note : Fixed windows shine in problems where the window size is predetermined and every result must be computed over that exact length. They’re widely used in financial indicators (moving averages), system monitoring (rolling CPU usage) and signal processing (sliding filters).

Examples

  • Average of All Subarrays of Size K
  • Maximum Sum Subarray of Size K
  • Minimum Sum Subarray of Size K
  • Maximum Number of Vowels in a Substring of Length K
  • Number of Subarrays of Size K with Distinct Elements
  • First Negative Integer in Every Window of Size K
  • Max/Min Element in Every Window of Size K
  • Count of Subarrays of Size K with Sum Divisible by M
  • Longest Subarray with Average ≥ Target (fixed k constraint)
  • K-Band Frequency Problem : In a stream of logs, track frequency counts in every window of size k.
  • Stock Analysis (Rolling Window Indicator) : Given stock prices, compute moving average or max gain over every k-day window.

2. Variable Window

A Variable Window (also called a dynamic-size sliding window) is a window that changes its size on the fly. It expands to include new elements and shrinks whenever the current state violates problem constraints. Unlike a fixed window where the size is constant, the variable window adapts to conditions as it moves.

When to Use

You should reach for a variable window when solving problems that demand

  • Maintaining validity under a condition (e.g., no duplicate characters, sum within a limit).
  • Tracking maximum/minimum range lengths that satisfy a constraint.
  • Adapting the window size to optimize something (length, count, cost).
  • Streaming/real-time: maintain user sessions, detect anomalies within thresholds.

Variable windows are best suited for problems where you must adaptively balance conditions while scanning the sequence. They’re widely applied in string problems (unique characters, frequency limits), subarray problems (target sum), and real-time monitoring systems where conditions may vary dynamically.

Example : Longest Substring Without Repeating Characters

Copy
import java.util.*;

public class LongestSubstringWithoutRepeating {
    
    public static int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> map = new HashMap<>();
        int left = 0, maxLength = 0;
        for (int right = 0; right < s.length(); right++) {
            char c = s.charAt(right);
            if (map.containsKey(c) && map.get(c) >= left) {
                left = map.get(c) + 1;
            }
            map.put(c, right);
            maxLength = Math.max(maxLength, right - left + 1);
        }
        return maxLength;
    }
 
    public static void main(String[] args) {
        System.out.println("Length of longest substring: " + lengthOfLongestSubstring("abcabcbb")); // 3
        System.out.println("Length of longest substring: " + lengthOfLongestSubstring("bbbbb")); // 1
        System.out.println("Length of longest substring: " + lengthOfLongestSubstring("pwwkew")); // 3
    }
}
Length of longest substring: 3
Length of longest substring: 1
Length of longest substring: 3

Classic Examples

  • Longest Substring Without Repeating Characters
  • Longest Subarray with Sum ≤ K : Variation where you expand until sum exceeds k, then shrink.
  • Longest Substring with At Most K Distinct Characters
  • Longest Substring with At Most K Repeating Characters
  • Longest Subarray with Product Less Than K
  • Fruits Into Baskets : Longest subarray with at most 2 distinct integers.
  • Longest Subarray of 1s After Deleting One Element : Shrink window to maintain at most one zero.
  • Max Consecutive Ones III : Longest subarray containing at most k zeros. (LeetCode 1004).
  • Longest Subarray of Sum Divisible by K

Tip : Start with longest substring problems (clear and visual) → move to numeric subarrays with constraints → then tackle minimum window substring, which is the hardest but most instructive.

3. Dynamic Window

A Dynamic Window is a sliding window that doesn’t follow a fixed growth pattern. Instead, it expands and contracts unpredictably as the algorithm works to satisfy a target condition. Unlike a fixed window (constant size) or a simple variable window (mostly expands until it violates a condition), the dynamic window may require both aggressive expansion and frequent shrinking to find the optimal solution.

When to Use

Dynamic windows are useful when the problem

  • Has a variable constraint threshold (e.g., sum ≥ target, product ≤ k).
  • Requires finding the minimum or maximum length subarray/substring that meets a condition.
  • Involves optimizing resources under a bound (e.g., minimum cost, minimum size, maximum utilization without overflow).
  • Network and streaming systems where load varies dynamically.

Example : Smallest Subarray with Sum ≥ Target

Given an array of positive integers nums and a positive integer target, find the minimal length of a contiguous subarray [nums[l], nums[l+1], ..., nums[r]] of which the sum is greater than or equal to target. If there is no such subarray, return 0.

Copy
public class SmallestSubarraySum {

    public static int minSubArrayLen(int target, int[] nums) {
        int left = 0, sum = 0, minLength = Integer.MAX_VALUE;
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];
            while (sum >= target) {
                minLength = Math.min(minLength, right - left + 1);
                sum -= nums[left];
                left++;
            }
        }
        return (minLength == Integer.MAX_VALUE) ? 0 : minLength;
    }

    public static void main(String[] args) {
        int[] nums = {2, 3, 1, 1, 2, 4, 2, 3};
        int target = 7;
        System.out.println("Smallest subarray length: " + minSubArrayLen(target, nums));
    }
}
Smallest subarray length: 3

Classic Examples

  • Smallest Subarray with Sum ≥ Target : Expand until sum ≥ target, then shrink aggressively. (LeetCode 209)
  • Minimum Window Substring : Find smallest substring containing all characters of t. (LeetCode 76)
  • Minimum Size Subarray Sum (Circular variation) : Variant of LC 209, sometimes asked in contests.
  • Shortest Subarray with At Least K Sum : needs deque for optimization, still shrinking logic applies. (LeetCode 862 Harder)
  • Minimum Window Subsequence : Find the smallest substring of s containing t as a subsequence. (LeetCode 727)
  • Smallest Substring of All Distinct Characters
  • Shortest Subarray with Exactly K Distinct Integers : Advanced variant, uses two sliding windows.
  • Shortest Subarray with Sum Divisible by K : Sometimes prefix sums + hashmap, but can be approached with dynamic shrinking in constraints.
  • Minimum Length Substring with Frequency Constraints : find smallest substring where each character appears at least X times.
  • Minimum Size Subarray to Remove for Array Sum Divisible by p : prefix + dynamic shrinking. (LeetCode 1590)

Difference Between Variable and Dynamic Sliding Window

Aspect Variable Sliding Window Dynamic Sliding Window
Definition Window size adjusts (expands/shrinks) to maintain a validity condition (e.g., uniqueness, ≤ K distinct elements). Window expands until a condition is satisfied, then shrinks aggressively to optimize (usually minimize) the window.
Growth Pattern Expand until violation → shrink just enough to restore validity (lazy shrink). Expand until condition met → shrink repeatedly to find the tightest window (greedy shrink).
Common Use Case Longest / maximum substring or subarray problems. Smallest / minimum substring or subarray problems.
Goal Maximize the valid window length. Minimize the valid window length (or tightly optimize it).
Complexity Typically O(n), straightforward sliding logic. Typically O(n), but shrinking logic is trickier to implement correctly.
Mental Model “How far can I stretch the window while staying valid?” “How much can I shrink the window while still valid?”
Examples - Longest Substring Without Repeating Characters (LC 3)
- Fruits Into Baskets (LC 904)
- Max Consecutive Ones III (LC 1004)
- Smallest Subarray with Sum ≥ Target (LC 209)
- Minimum Window Substring (LC 76)
- Shortest Subarray with Sum ≥ K (LC 862)

Sliding Window FAQs

1. What is the Sliding Window technique?

Sliding Window is a two-pointer pattern where you maintain a contiguous subarray or substring by adjusting left and right pointers. It avoids recomputation and reduces time complexity compared to brute force.

2. Can Sliding Window be applied on linked lists?

Yes, but less common. Works when you only need sequential access (sum, count). Random access problems are better on arrays/strings.

3. When should I use Sliding Window?

  • When dealing with subarrays/substrings (continuous segments).
  • When the problem requires sum, max/min, frequency, or distinct count inside a range.
  • When brute force is O(n²) but you can reuse computations in O(n).

4. Is Sliding Window the same as Two Pointers?

Not exactly.

  • Two Pointers = broader pattern (e.g., pair sum, merging intervals).
  • Sliding Window = specialized form of two pointers that always keeps a contiguous range.

5. What’s the difference between Variable and Dynamic Sliding Window?

  • Variable Window → “Expand until violation, shrink just enough” (maximize).
  • Dynamic Window → “Expand until valid, shrink aggressively” (minimize).

6. What’s the typical complexity of Sliding Window?

Most problems can be solved in O(n) because each pointer moves at most n steps. But:

  • Fixed window is simplest → O(n).
  • Variable/Dynamic require condition checks → still O(n), but with heavier logic.
  • Some edge cases (like Shortest Subarray with Sum ≥ K) require extra DS → O(n log n).

7. Can Sliding Window handle negative numbers?

When working with negative numbers Be careful

  • Fixed window → works fine.
  • Variable/Dynamic window → tricky if conditions depend on sums, because shrinking/expanding assumptions break with negatives. Often you need prefix sums or monotonic deque instead.

8. What data structures are often used with Sliding Window?

  • HashMap / Counter : track frequencies, distinct chars.
  • Deque : track max/min in window (Monotonic Queue pattern).
  • Set : track uniqueness.
  • Prefix sums : handle negative numbers, modular constraints.

9. What are the most common interview problems on Sliding Window?

  • Maximum Sum Subarray of Size k (fixed).
  • Longest Substring Without Repeating Characters (variable).
  • Smallest Subarray with Sum ≥ Target (dynamic).
  • Minimum Window Substring (dynamic).
  • Sliding Window Maximum (deque optimization).

10. What are the common pitfalls?

  • Forgetting to shrink properly when condition breaks.
  • Off-by-one errors when calculating window length (right - left + 1).
  • Assuming it works with negatives when it doesn’t.
  • Forgetting to update global answer after shrinking, not just while expanding.

11. What’s the role of Monotonic Queue in Sliding Window?

It helps solve problems like Sliding Window Maximum/Minimum in O(n), instead of O(n log n). The queue stores indices in increasing/decreasing order to quickly access max/min in the window.

12. How to know if a problem is Sliding Window?

Look for keywords in the statement

  • “subarray” or “substring”
  • “contiguous”
  • “at most k / at least k”
  • “longest / smallest” range

13. Why Do Interviewers Love Sliding Window?

Sliding Window is a favorite in interviews because it’s simple on the surface yet powerful in application. It reveals whether a candidate can

  • Spot patterns in brute force solutions and optimize them from O(n²) to O(n).
  • Think incrementally : updating results on-the-fly rather than recalculating from scratch.
  • Handle tricky edge cases like dynamic shrinking, negatives, varying conditions and hashmaps.
  • Balance correctness with efficiency, a skill crucial in real-world system design as well as algorithmic coding.

In short: mastering Sliding Window shows you can turn a naive idea into an efficient, production-ready solution.

14. What’s the Difference Between Sliding Window and Prefix Sum Techniques?

Sliding Window : Best for dynamic or online processing where the window expands/shrinks as you move left & right. Ideal when you need to maintain running information (sum, count, distinct elements) efficiently as the window changes.

Prefix Sum : Best for static queries where you want the sum (or similar property) of any fixed subarray in O(1) after O(n) preprocessing. Perfect for repeated range queries on an immutable array.

Rule of Thumb
  • Use Sliding Window when the problem is about moving ranges in real time.
  • Use Prefix Sum when the problem is about answering queries on any arbitrary subarray.

15. Can Sliding Window be used on streams of data (not arrays)?

Yes . It’s widely used in real-time systems (network packet analysis, log monitoring, rolling averages) where data arrives continuously and you only store what’s inside the current window.