Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 6

Sliding Window Technique for Subarrays and Substrings

Recommended resources

Introduction

In our previous lessons, we've established a foundation with core data structures like arrays, strings, and most recently, hash maps. You've seen how hash maps provide O(1) average time complexity for lookups, a significant improvement over the O(n) scan required for arrays. Today, we shift from data structures to a powerful algorithmic pattern that leverages these linear structures: the sliding window technique.

This lesson is dedicated to mastering this technique to efficiently solve problems involving contiguous subarrays or substrings. Many interview questions that seem to require a brute-force O(n^2) approach can be optimized to a linear O(n) solution using a sliding window. We will break this down into its two primary forms: the fixed-size window and the variable-size window, ensuring you can identify which to apply and implement it effectively. This is a crucial pattern for any technical interview involving array or string manipulation.


The Problem with Brute-Force Subarray Analysis

Imagine you're asked to solve a common problem: "Given an array of integers, find the maximum sum of any contiguous subarray of size k."

A straightforward, brute-force approach would be to:

  1. Generate every possible subarray of size k.
  2. Calculate the sum of each subarray.
  3. Keep track of the maximum sum found.

This approach works, but it's inefficient. As you analyze overlapping subarrays, you end up re-calculating the sum of the same elements repeatedly.

The following video provides an excellent visual breakdown of this naive strategy and analyzes its time complexity. Understanding this inefficiency is key to appreciating the elegance of the sliding window solution.

Sliding Window Algorithm for Tech Interviews - Full Course

Watch the "max subarray sum size K" section from the freeCodeCamp.org video.

Watch from the beginning of the problem description at the explanation of the naive approach. Pay close attention to how the presenter analyzes the time complexity as O(n*k). This sets the stage for the optimization to come.


The Fixed-Size Sliding Window: An Elegant Optimization

The key insight of the sliding window technique is that as the window "slides" one position to the right, you only need to account for two elements: the one leaving the window and the one entering it. There's no need to re-sum the elements that remain in the window.

This simple adjustment transforms the algorithm.

This diagram illustrates the core optimization. Instead of recomputing the sum of the entire new window, you update the old sum by subtracting the outgoing element and adding the incoming one.

The same freeCodeCamp.org video continues by explaining this optimized approach, which reduces the time complexity to a much more efficient O(n).

Sliding Window Algorithm for Tech Interviews - Full Course

Continue with the same video to see the optimized sliding window approach.

Watch the segment from the optimized solution. Focus on the logic of maintaining a current_sum and updating it by subtracting the trailing element and adding the leading element. This is the fundamental pattern for all fixed-size window problems.

Implementing the Fixed-Size Window

Let's solidify this with a Python implementation for the "Maximum Sum Subarray of Size K" problem. The logic follows the video's explanation precisely.

def max_sum_subarray(arr, k):
    if len(arr) < k:
        return 0 # Or handle error appropriately




    # 1. Calculate the sum of the initial window
    window_sum = sum(arr[:k])
    max_sum = window_sum




    # 2. Slide the window from k to the end of the array
    for i in range(k, len(arr)):



        # Update the window sum in O(1)
        # Subtract the element that's leaving the window
        # Add the element that's entering the window
        window_sum = window_sum - arr[i-k] + arr[i]
        



        # 3. Update the maximum sum found
        max_sum = max(max_sum, window_sum)
        
    return max_sum




# Example
arr = [1, 4, 2, 10, 23, 3, 1, 0, 20]
k = 4
print(f"The maximum sum is: {max_sum_subarray(arr, k)}") # Output: 39

Notice how the loop runs from k to len(arr). Inside the loop, every operation—subtraction, addition, and comparison—is O(1). This is what gives the algorithm its overall O(n) time complexity.


The Variable-Size Sliding Window

Not all problems provide a fixed size k. Often, you're asked to find the longest or shortest subarray that satisfies a certain condition. This is where the variable-size sliding window comes in.

The strategy here is slightly different:

  1. Expand the window by moving the right pointer (R).
  2. While the window is valid (i.e., satisfies the condition), record its properties (e.g., length) and continue expanding.
  3. If the window becomes invalid (violates the condition), shrink it by moving the left pointer (L) until it becomes valid again.
The window is the contiguous subarray defined by the Left and Right pointers. In a variable-size window, both pointers move to expand and shrink the window dynamically.

A classic problem for this pattern is LeetCode #3: "Longest Substring Without Repeating Characters". Here, the "condition" is that the substring must contain only unique characters.

The following video provides a clear walkthrough of this variable-size pattern.

Sliding Window Algorithm - Variable Length + Fixed Length - DSA Course in Python Lecture 13

Watch this segment from Greg Hogg's video to understand the variable-length sliding window.

Focus on the explanation for "Longest Substring Without Repeating Characters" from this section. The key logic to grasp is the use of a for loop for the right pointer to expand the window and a while loop to contract the window from the left whenever a duplicate character is found. The use of a set to track characters in the current window is a perfect practical application of the data structures we've covered.

Recognizing Sliding Window Problems

Now that you've seen both patterns, how do you identify problems where this technique is applicable? The following reading provides excellent clues.

Mastering Sliding Window Techniques: A Comprehensive Guide for Coding Interviews – AlgoCademy Blog

This article from AlgoCademy succinctly summarizes when to use the sliding window technique and formally defines the two types we've just discussed.

Please read the introduction and the first two main sections: this part of the article. Pay close attention to the "Key Characteristics of Sliding Window Problems." These are the signals to look for in a problem description during an interview.

The core characteristics are:

  • The problem involves an ordered, iterable data structure (array, list, string).
  • You are asked to find a result over a contiguous subarray or substring.
  • The problem can often be solved with a brute-force approach that involves nested loops, signaling an opportunity for optimization.

Conclusion

In this lesson, we've added a fundamental algorithmic pattern, the sliding window, to your problem-solving toolkit. It's an essential technique for optimizing solutions to many common interview questions involving arrays and strings.

Key Takeaways:

  • Purpose: The sliding window technique converts inefficient brute-force solutions (often O(n^2) or O(n*k)) for contiguous subarray/substring problems into highly efficient linear time (O(n)) solutions.
  • Fixed-Size Window: Used when the problem specifies a fixed window size k. The core logic is to maintain a running state (like a sum) and update it in O(1) time by subtracting the outgoing element and adding the incoming one.
  • Variable-Size Window: Used when the window size is not fixed. The core logic involves expanding the window with a right pointer and shrinking it with a left pointer whenever a specific condition is violated.
  • Recognition: Look for problems that ask for something (max, min, longest, shortest, count) over a contiguous block of elements in a linear data structure.

Next, we will explore another powerful array-based technique: prefix sums. While sliding windows are ideal for analyzing contiguous subarrays themselves, prefix sums provide a way to calculate the sum of any arbitrary range [i, j] in O(1) time after an initial O(n) pre-computation.