Skip to main content

Welcome to a Grasp lesson

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

Lesson 21

Sliding Window for Subarrays and Substrings

Recommended resources

Hello! Welcome to the next lesson in our module on "Two-Pointers and Sliding Window."

In our last session, we distinguished between the two main two-pointer patterns: the opposite-end and the fast/slow pointer techniques. You learned that they differ in their setup, movement, and the types of problems they solve.

Today, we'll build on the idea of pointers moving in the same direction to explore a powerful and highly efficient technique for competitive programming: the sliding window. Specifically, our goal is to use the fixed-size sliding window technique to solve subarray and substring problems. This method is your key to transforming slow, brute-force solutions into sleek, linear-time algorithms.

What is a Sliding Window?

At its heart, the sliding window technique is an optimization. It's designed for problems where you need to find something in a contiguous block of data, like a subarray or a substring.

Imagine you have a long array and you need to find the subarray of a specific size, say k=3, that has the largest sum.

The brute-force way would be:

  1. Look at the first three elements, calculate their sum.
  2. Look at elements 2 through 4, calculate their sum.
  3. Look at elements 3 through 5, calculate their sum.
  4. ...and so on, keeping track of the biggest sum you find.

This works, but it's inefficient. For each window, you're re-summing elements you've already summed before. The sliding window technique eliminates this redundant work.

To see this inefficiency and the clever solution, watch the first couple of minutes of the following video.

Sliding Window Technique

This video from Profound Academy provides an excellent contrast between the naive approach and the optimized sliding window technique for finding the maximum sum of a fixed-size subarray.

Watch from the beginning (00:00) to 02:28. Pay close attention to the explanation of why the naive O(N*K) approach is slow and how the sliding window reduces the work at each step to achieve O(N) complexity.

As the video explained, instead of re-calculating the sum for each new window, you can simply "slide" the window forward by one position.

Sliding Window Algorithm Illustration
This image shows the basic movement of a fixed-size sliding window. The window of three elements moves one position to the right, efficiently transitioning from one subarray to the next.

When you slide the window, you just need to:

  1. Subtract the element that is no longer in the window (the one on the far left).
  2. Add the new element that has just entered the window (the one on the far right).

This way, you perform only two operations per step, regardless of how large the window is. This simple idea is what reduces the complexity from to a much faster .


A Step-by-Step Example: Maximum Subarray Sum

Let's trace this logic with a concrete example.
Problem: Given arr = [1, 2, 6, 2, 4, 1] and k = 3, find the maximum sum of any contiguous subarray of size 3.

Step 1: Initialize the Window

  • Calculate the sum of the first window (k=3 elements): 1 + 2 + 6 = 9.
  • Our current_sum is 9.
  • Our max_sum so far is also 9.

Step 2: Slide the Window to the Right

  • The window moves to cover [2, 6, 2].
  • To get the new sum, we take the current_sum (9), subtract the element leaving (1), and add the element entering (2).
  • new_sum = 9 - 1 + 2 = 10.
  • Our current_sum is now 10.
  • We update max_sum because 10 is greater than 9. max_sum is now 10.

Step 3: Slide Again

  • The window moves to cover [6, 2, 4].
  • new_sum = 10 - 2 + 4 = 12.
  • current_sum is now 12.
  • We update max_sum because 12 is greater than 10. max_sum is now 12.

Step 4: Slide to the End

  • The window moves to cover [2, 4, 1].
  • new_sum = 12 - 6 + 1 = 7.
  • current_sum is now 7.
  • max_sum remains 12, since 7 is smaller.

We've reached the end of the array. The maximum sum we found is 12.

Fixed-Size Sliding Window Technique for Maximum Subarray Sum
This diagram shows the process we just walked through. It visualizes how the current and maximum sums are updated as the window slides across the array.

From Logic to Code: A LeetCode Problem

Now let's see how to implement this in Python by solving a classic LeetCode problem. The problem is "Maximum Average Subarray I," which is a slight variation of what we just did—instead of the max sum, we want the max average. The core logic remains identical.

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

The video 'Sliding Window Algorithm' by Greg Hogg provides a fantastic, clear walkthrough of a fixed-length sliding window problem. He explains the logic, visualizes the process, and codes the solution in Python.

Please watch from 12:23 to 20:26. This segment covers the problem statement, a visual demonstration of the sliding window, and the full Python implementation with a complexity analysis. This is a direct application of our learning outcome.

Code Implementation Summary

Here is a Python function that implements the logic for the maximum sum problem, based on the principles from the video.

def max_sum_subarray(nums, k):
    # 1. Handle edge case
    if len(nums) < k:
        return 0

    # 2. Calculate the sum of the first window
    current_sum = sum(nums[:k])
    max_sum = current_sum

    # 3. Slide the window from the k-th element to the end
    for i in range(k, len(nums)):
        # Subtract the element leaving the window and add the element entering
        current_sum = current_sum - nums[i - k] + nums[i]
        
        # Update the maximum sum found so far
        max_sum = max(max_sum, current_sum)
        
    return max_sum

# Example usage:
arr = [1, 2, 6, 2, 4, 1]
k = 3
print(f"The maximum sum is: {max_sum_subarray(arr, k)}")  # Output: The maximum sum is: 12

This code snippet is an optimized version from the article "Competitive Programming #1: Sliding Window Technique" on Medium.

  • Time Complexity: . We iterate through the array once to build the initial sum (or we can do it in the main loop), and then one more time to slide the window. Each element is added to and subtracted from the sum exactly once.
  • Space Complexity: . We only use a few variables to store the current sum, max sum, and loop indices, regardless of the input array's size.
Test your understanding!

You are given an array nums = [10, 4, 2, 5, 6, 3, 8, 1] and a window size k = 3.

Your task is to find the minimum average of a contiguous subarray of size k. How would you adapt the max_sum_subarray logic to solve this? What would be the final answer?

Show answer

To find the minimum average, you would make two small changes:

  1. Initialize a min_sum variable instead of max_sum. Start it with the sum of the first window.
  2. In the loop, update min_sum using min(min_sum, current_sum) instead of max().
  3. Finally, return min_sum / k.

Let's trace it:

  • Initial window [10, 4, 2]: sum = 16. min_sum = 16.
  • Slide to [4, 2, 5]: current_sum = 16 - 10 + 5 = 11. min_sum becomes 11.
  • Slide to [2, 5, 6]: current_sum = 11 - 4 + 6 = 13. min_sum remains 11.
  • Slide to [5, 6, 3]: current_sum = 13 - 2 + 3 = 14. min_sum remains 11.
  • Slide to [6, 3, 8]: current_sum = 14 - 5 + 8 = 17. min_sum remains 11.
  • Slide to [3, 8, 1]: current_sum = 17 - 6 + 1 = 12. min_sum remains 11.

The minimum sum found is 11. The minimum average is 11 / 3 = 3.66....


Conclusion

Today you've mastered the fixed-size sliding window, a fundamental technique for your competitive programming toolkit. It's a simple yet powerful idea that can dramatically speed up your solutions for problems on contiguous subarrays and substrings.

Key Takeaways:

  • Fixed-size sliding window is an optimization technique for problems on contiguous data blocks of a constant size k.
  • It avoids redundant calculations by efficiently updating a running value (like a sum or count) as the window moves.
  • The core mechanic is to subtract the outgoing element and add the incoming element at each step.
  • This approach reduces the time complexity from a brute-force to an optimal .

Up Next:
The real power of sliding windows comes when the window size isn't fixed. In our next lesson, we will explore the variable-size sliding window technique. You'll learn how to expand and shrink a window dynamically to find subarrays or substrings that satisfy a condition, such as finding the shortest subarray whose sum is at least a certain value.