Welcome to our next lesson. In the previous sessions, we focused on fundamental string manipulation problems, culminating in finding the longest common prefix. We saw how a clever observation—like sorting the strings—could dramatically simplify the problem. Today, we shift our focus from strings to a powerful and versatile algorithmic pattern used for both arrays and strings: the sliding window technique.
This lesson introduces the core concept of a sliding window, starting with its most straightforward application: a window of a fixed size. You will learn how to apply this technique to solve a classic problem: finding the maximum sum of a contiguous subarray of a given size k. As per your preference, we will first analyze a simple brute-force approach and then develop the more efficient, optimal sliding window solution.
1. The Problem: Maximum Sum Subarray of Size K
Let's begin by clearly defining the problem. You are given an array of integers and a number k. Your task is to find the maximum sum that can be obtained from any contiguous subarray of size exactly k. A contiguous subarray is a sequence of adjacent elements.
For example, consider the array arr = [1, 7, 6, 2, 3, 4, 5] and k = 2.
The subarrays of size 2 are: [1, 7], [7, 6], [6, 2], [2, 3], [3, 4], and [4, 5].
Their sums are: 8, 13, 8, 5, 7, and 9.
The maximum among these sums is 13.

To formalize this, let's review the problem statement from GeeksforGeeks.
Maximum sum of a subarray of size k
This article from GeeksforGeeks provides a clear definition and several examples of the problem we're about to solve.
Read the problem statement and examples at the top of the page. This will help solidify your understanding of the input and the expected output.
2. Approach 1: The Brute-Force Method
Following our established method, let's start with the most intuitive, brute-force solution. The idea is straightforward:
- Generate every possible contiguous subarray of size
k. - Calculate the sum of each of these subarrays.
- Keep track of the maximum sum found so far.
To implement this, we can use two nested loops. The outer loop (i) will determine the starting index of our subarray. Since a subarray of size k cannot start past n-k (where n is the array length), this loop will run from 0 to n-k. The inner loop (j) will then iterate k times from the starting index i to sum up the elements of the current window.
The following video provides an excellent, detailed explanation of this naive approach.
Solve Subarray Problems Quickly With Sliding Window Technique | FREE DSA Course in JAVA | Lecture 79
This video from TAP ACADEMY breaks down the brute-force solution before introducing the sliding window.
Watch the section from this timestamp. It explains the logic of using nested loops, how to manage the current and maximum sums, and correctly determines the loop boundaries. The visualization of the i and j pointers is particularly helpful.
Now, let's look at the implementation and complexity from your primary resource, the takeuforward article.
Sliding Window Technique - Tutorial
This is the TUF article on the sliding window technique. We will first examine its explanation of the brute-force method.
Read the section that breaks down the brute-force logic with an example. Study the Java code provided for this approach. Finally, review the complexity analysis. The time complexity is O(N \cdot K) because for each of the N-K+1 possible windows, we do K additions. The space complexity is O(1).
This brute-force solution is correct, but as you'll see in interviews, correctness is just the first step. For large arrays, an solution can be too slow. This inefficiency motivates our search for an optimal approach.
3. The Sliding Window: A More Efficient Paradigm
The inefficiency in the brute-force method comes from recalculating the sum of each window from scratch. Consider the windows [1, 7, 6] and [7, 6, 2]. They share two elements, 7 and 6. When we move from the first window to the second, we are performing redundant calculations by re-adding 7 and 6.
The sliding window technique eliminates this redundancy. Imagine a "window" of size k that slides over the array. As it slides one step to the right:
- A new element enters the window from the right.
- An old element leaves the window from the left.
To update the sum, we simply take the sum of the previous window, subtract the element that left, and add the element that entered. This is an operation per slide.
This simple video from TAP ACADEMY provides a great analogy to build intuition.
Solve Subarray Problems Quickly With Sliding Window Technique | FREE DSA Course in JAVA | Lecture 79
This short segment gives a memorable, real-world analogy for the sliding window concept.
Watch from this timestamp to see the analogy of a physical window sliding across a scenic view. It effectively illustrates how the view (our subarray) changes incrementally.
4. Approach 2: The Optimal Sliding Window Solution
Now, let's formalize the sliding window algorithm for our problem:
- Initialization: Calculate the sum of the first
kelements. This is the sum of our initial window. InitializemaxSumwith this value. - Sliding: Start a loop from the
k-th index to the end of the array. In each step, this loop represents the new element entering the window.- Update the current window's sum by adding the new element (
arr[i]) and subtracting the element that just slid out of the window's left side (arr[i-k]). - Compare this updated window sum with
maxSumand updatemaxSumif the new sum is larger.
- Update the current window's sum by adding the new element (
- Result: After the loop finishes,
maxSumwill hold the maximum sum of any subarray of sizek.
This process involves a single pass through the array, making it much more efficient. The following video walks through this entire optimal process, from the initial sum calculation to the sliding logic and the final Java implementation.
Solve Subarray Problems Quickly With Sliding Window Technique | FREE DSA Course in JAVA | Lecture 79
This is a comprehensive walkthrough of the optimal solution.
First, watch the section on calculating the initial window sum. Next, see the detailed explanation of the sliding mechanism, showing how to subtract the outgoing element and add the incoming one. Finally, follow the complete Java code implementation, which puts all the pieces together.
To solidify this, let's turn back to the Striver/TUF article, which is our main guide. It presents the same logic in a concise format.
Sliding Window Technique - Tutorial
Now, we'll study the optimal solution from the TUF article.
Start by reading the Algorithm section for the sliding window technique. It clearly lays out the observation about reusing the sum. Carefully examine the Java code for the optimal solution. Notice how it first computes the sum of the initial window and then enters a single loop to slide the window across the rest of the array. Finally, read the complexity analysis. The time complexity is now O(N), a significant improvement, and the space complexity remains O(1).
By applying the sliding window pattern, we transformed an algorithm into a linear time solution, which is the kind of optimization interviewers look for.
Conclusion
In this lesson, we introduced the powerful sliding window technique by applying it to a concrete problem. This pattern is fundamental for efficiently solving problems involving contiguous subarrays or substrings.
Key Takeaways:
- Problem: Find the maximum sum of a contiguous subarray of a fixed size
k. - Brute-Force Solution: Use nested loops to check every possible subarray of size
k. This results in an time complexity. - Sliding Window Insight: Instead of recalculating sums, we can maintain a "window" of size
kand slide it across the array. The sum is updated in time at each step by subtracting the leaving element and adding the entering one. - Optimal Solution: This leads to an elegant single-pass algorithm with time complexity and space complexity.
You've now mastered the fixed-size sliding window. In our next lesson, we will build on this foundation to tackle problems where the window size is not fixed. We'll explore variable-size sliding windows to solve problems like finding the "longest substring without repeating characters."