In our last lesson, we explored the two-pointer technique, a powerful pattern for optimizing problems on sorted arrays and strings by moving pointers from opposite ends. Today, we'll delve into a closely related and equally important pattern: the sliding window technique. This approach is your key to solving a whole class of problems that involve finding an optimal contiguous subarray or substring.
Your goal for this lesson is to learn how to apply the sliding window technique to transform brute-force solutions, which are often inefficient, into highly optimized linear-time solutions. We will focus on the classic problem of finding the maximum sum of a subarray of a fixed size, which is a common question in SDE interviews and a perfect illustration of this pattern's power.
The Essence of the Sliding Window
Imagine you have a long sequence of data, like an array or a string. A brute-force approach to finding the best subarray might involve examining every single possible subarray. For an array of size , this could mean looking at subarrays, leading to slow algorithms.
The sliding window technique offers a much smarter way. It maintains a "window" β a contiguous block of elements β and slides this window across the data structure. The key insight is that as the window slides one position over, you don't need to re-calculate everything. You simply update your metrics by incorporating the new element that enters the window and removing the one that leaves.
This simple update step is what makes the technique so efficient. Because each element is processed only twice (once when it enters the window and once when it leaves), the overall time complexity is typically reduced to .
To understand this core idea, let's first get a high-level overview.
A Complete Beginner-Friendly Guide (with Java Examples)
This article by Urmila Unni provides a clear and concise introduction to the sliding window pattern.
Please read the first three sections: the introduction, which explains the basic concept, and the next section, the checklist, which gives you valuable hints for identifying when this pattern is applicable. Pay close attention to the reasoning behind its O(n) time complexity.
The fundamental mechanism of the sliding window is based on two pointers, typically left and right, which define the boundaries of the current window. The window is manipulated through three basic operations: expanding, shrinking, and sliding.

There are two primary types of sliding window problems:
- Fixed-Size Window: The size of the window,
k, is predetermined. The window slides one element at a time from the beginning to the end. - Variable-Size Window: The window size changes dynamically. It grows by moving the
rightpointer and shrinks by moving theleftpointer to satisfy a certain condition.
Today, we'll master the fixed-size window and get a first look at the variable-size pattern.
Application 1: Fixed-Size Window - Maximum Sum Subarray of Size k
This is a canonical problem for the sliding window pattern and directly addresses today's learning outcome.
Problem: Given an array of integers arr and a positive integer k, find the maximum sum of any contiguous subarray of size k.
A naive solution would involve a nested loop: the outer loop picks a starting index, and the inner loop sums the next k elements. This results in an time complexity. With the sliding window, we can do much better.
The video below provides an excellent walkthrough of this exact problem, comparing the brute-force method with the optimized sliding window approach.
Coding Interview Patterns - Sliding Window | 10 different problems in a single video
This video from Nikhil Lohia's channel breaks down the sliding window pattern starting with this fundamental example.
Watch the segment from the problem explanation. The presenter clearly demonstrates how to calculate the initial sum and then efficiently update it as the window slides, avoiding redundant calculations.
As the video explained, the logic is as follows:
- Initialize: Calculate the sum of the first
kelements. This is your initialwindowSumand your initialmaxSum. - Slide: Iterate from the
k-th element to the end of the array. In each iteration:- Add the new element (
arr[i]) towindowSum. - Subtract the element that just fell out of the window (
arr[i - k]).
- Add the new element (
- Update: After each slide, compare the new
windowSumwithmaxSumand updatemaxSumif the new sum is larger.
The image below perfectly captures this process.

Now, let's look at a clean Java implementation of this technique.
A Complete Beginner-Friendly Guide (with Java Examples)
Let's return to the guide by Urmila Unni to see the code.
Focus on the section Type 1: Fixed-Size Window. Analyze the maxSumSubarray method. Notice how the first loop handles the initial window and the second loop implements the sliding and updating logic. This is a direct translation of the concept we've been discussing.
This approach has a time complexity of because we iterate through the array only once. The space complexity is as we only use a few variables to store the sum and pointers.
Application 2: A Glimpse into Variable-Size Windows
While our main goal is mastering the fixed-size window, it's essential to be aware of its more dynamic counterpart, which you will frequently encounter in interviews. In variable-size window problems, the window expands and shrinks to meet a certain condition.
A classic example is: Find the length of the smallest contiguous subarray whose sum is greater than or equal to a target value S.
Here, the window, defined by left and right pointers, operates as follows:
- Expand: The
rightpointer always moves forward, adding the new element to the window's sum. - Shrink: As soon as the window's sum meets the condition (i.e.,
sum >= S), we record the window's length and then shrink the window from the left by moving theleftpointer forward until the condition is no longer met. We repeat this process, always trying to find the smallest possible window that satisfies the condition.
The article we've been using has a great section on this.
A Complete Beginner-Friendly Guide (with Java Examples)
This section will introduce you to the logic behind dynamic windows.
Read the section on Type 2: Variable-Size Window. Pay attention to the while loop nested inside the for loop. This is the typical structure for a variable-size window: the for loop expands the window, and the while loop shrinks it when a condition is met.
We will revisit this and other advanced patterns later, but understanding this fundamental expand-and-shrink logic is a great first step.
How to Spot a Sliding Window Problem
In a high-pressure interview setting, recognizing the right pattern is half the battle. Here are some strong indicators that a problem might be a good fit for the sliding window technique:
- The problem involves a contiguous subarray or substring.
- You are asked to find a maximum, minimum, longest, or shortest subarray/substring that satisfies some property.
- Keywords like "subarray of size k," "at most k distinct characters," or "sum greater than S" are present.
- A brute-force solution seems to involve nested loops, suggesting a potential for optimization.
For a more structured thought process to use during interviews, this is a valuable resource.
A Complete Beginner-Friendly Guide (with Java Examples)
This final section of the guide consolidates the strategy.
Read the sections "How to Think During Interviews" and "Popular Interview Questions by Category". This provides a step-by-step mental checklist and a list of classic problems that will help you build pattern recognition.
Conclusion
Today, you've added another essential algorithmic pattern to your toolkit. The sliding window technique is a fundamental approach for optimizing problems that deal with contiguous segments of data, allowing you to craft elegant and efficient solutions.
Here are the key takeaways from this lesson:
- The sliding window technique processes arrays or strings by maintaining a contiguous window of elements and sliding it across the data.
- Its efficiency comes from updating calculations in time as the window slides, rather than re-computing from scratch. This reduces overall time complexity to .
- There are two main types: fixed-size (where window size
kis given) and variable-size (where the window expands and shrinks to meet a condition). - The pattern is identifiable by problem statements involving contiguous subarrays/substrings and finding an optimal (min, max, longest, etc.) segment.
In this lesson, we focused on finding optimal subarrays. But what if you needed to answer many range sum queries over an array, not just find one optimal range? For that, a different approach is more efficient. In our next lesson, we'll explore the prefix sum technique, which allows you to answer any range sum query in time after an initial preprocessing step.