Introduction
Hello! Welcome to your fifth lesson. In our last session, we mastered the convergent two-pointer technique, where pointers at opposite ends of an array move toward each other. This proved highly effective for problems involving sorted arrays and palindromic checks.
Today, we'll build on the two-pointer concept by exploring one of the most powerful patterns for array and string problems: the sliding window technique. Think of this as a variation where two pointers move in the same direction, creating a dynamic "window" that slides across the data. Mastering this pattern is crucial for efficiently solving a large category of problems that ask for the "longest," "shortest," or "best" contiguous subarray or substring that satisfies a certain condition.
By the end of this lesson, you will be able to identify problems suitable for the sliding window approach, differentiate between fixed-length and variable-length windows, and apply the correct logic to solve them in optimal linear time.
1. What is the Sliding Window Technique?
At its core, the sliding window technique is an optimization that avoids the redundant work of a brute-force approach. A naive solution to a subarray problem might involve nested loops to check every single possible subarray, often resulting in an O(n²) or even O(n³) time complexity.
The sliding window approach reduces this to O(n) time. It maintains a "window" (a sub-section of the array or string) using two pointers, often called left and right or start and end. The right pointer expands the window, and the left pointer contracts it. By intelligently sliding this window over the data, we only need to process each element a constant number of times.

There are two primary types of sliding windows, and knowing which one to use is key to solving problems effectively:
- Fixed-Length Sliding Window: Used when the problem specifies a subarray or substring of a fixed size,
k. - Variable-Length Sliding Window: Used when the problem asks for the longest or shortest subarray that satisfies a given condition.
Let's dive into each type.
2. Fixed-Length Sliding Window
This is the more straightforward variant. You use it when the problem statement explicitly gives you the window size, k. The core idea is to maintain a window of exactly size k and slide it across the array one step at a time.
The Logic:
- First, build the initial window by processing the first
kelements. - Calculate the desired value (e.g., sum, average) for this initial window.
- Then, iterate from the
k-th element to the end of the array. In each step:- Expand: Add the new element (at the
rightend) to your window's state. - Contract: Remove the element that is falling out of the window (at the
leftend) from your state. - Update your overall result (e.g., the maximum sum found so far).
- Expand: Add the new element (at the
This "add one, subtract one" process is what makes the algorithm so efficient.
Sliding Window Algorithm - Variable Length + Fixed Length - DSA Course in Python Lecture 13
Let's watch a clear explanation of this pattern with a classic example: 'Maximum Average Subarray'. This section from a video by Greg Hogg demonstrates how to build and slide a fixed-length window.
Watch from 12:41 to 18:16. Pay close attention to: How the initial window's sum is calculated. The loop that slides the window. The crucial step of adding the new element (nums[i]) and subtracting the old one (nums[i-k]) to maintain the running sum of the window.
Code and Complexity
As you saw in the video, the implementation is clean and efficient. Here's a general template for the fixed-length pattern.
def fixed_length_sliding_window(arr, k):
# Initialize variables to track window state and overall result
current_window_sum = 0
max_sum = float('-inf')
# Initialize pointers
left = 0
for right in range(len(arr)):
# Expand the window by adding the right element
current_window_sum += arr[right]
# Once the window reaches size k, start sliding
if right >= k - 1:
# Update the result with the current window's state
max_sum = max(max_sum, current_window_sum)
# Contract the window by removing the left element
current_window_sum -= arr[left]
left += 1
return max_sum
- Time Complexity: O(n), because each element is visited exactly once by the
rightpointer and once by theleftpointer. - Space Complexity: O(1), as we only use a few variables to store the state.
For additional reference, the article Fixed-Length Sliding Window from Hello Interview also provides a great template and explanation.
This article from Hello Interview provides a concise textual summary and a template for the fixed-length sliding window pattern. It's a good resource to bookmark for quick revision.
Read the sections 'Fixed-Length Sliding Window', 'Problem: Maximum Sum of Subarray with Size K', and the 'Template'. This will reinforce the concepts from the video. Estimated time: 5 minutes.
3. Variable-Length Sliding Window
This pattern is more dynamic and addresses a broader class of problems, making it very common in interviews. You use it when you need to find the longest or shortest contiguous subarray that satisfies some property.
Here, the window size is not fixed. It grows and shrinks based on whether a certain condition is met.
The Logic:
The core of this pattern is a while loop nested inside a for loop, which may seem like O(n²) but is actually O(n).
- Initialize
left = 0and a data structure to track the window's state (e.g., a hash map for character counts, a set for unique elements, a variable for the sum). - Iterate through the array with a
rightpointer from0ton-1. - Expand: At each step, add the element
arr[right]to your window's state. - Check and Contract: After expanding, check if the window's state is invalid (e.g., sum is too large, more than
kdistinct characters).- If it is, enter a
whileloop to contract the window from the left. - In the
whileloop, removearr[left]from the window's state and incrementleft. - Continue contracting until the window becomes valid again.
- If it is, enter a
- After any necessary contractions, the window is guaranteed to be valid. Update your result (e.g.,
max_length = max(max_length, right - left + 1)).
Let's look at two classic examples to see this in action.
Example 1: Longest Substring Without Repeating Characters
This problem asks for the longest substring with all unique characters. The "validity" condition is that the window must not contain any duplicate characters.
Sliding Window Algorithm - Variable Length + Fixed Length - DSA Course in Python Lecture 13
Let's return to the Greg Hogg video. The first part explains this exact problem, a quintessential variable-length window question.
Watch from 00:57 to 12:41. Focus on: The use of a set to track characters currently in the window. The condition for an 'invalid' window: when you try to add a character that's already in the set. How the while loop contracts the window from the left until the duplicate is removed and the window is valid again.
Example 2: Minimum Size Subarray Sum
This problem asks for the shortest contiguous subarray whose sum is greater than or equal to a target. The "validity" condition is current_sum >= target. The logic is slightly different because we want to shrink the window as soon as it becomes valid to find the minimum length.
Minimum Size Subarray Sum - Leetcode 209 - Python
Now, let's watch a NeetCode video on finding the minimum size subarray. This demonstrates how the pattern adapts when you're minimizing instead of maximizing.
Watch from 02:26 to 12:15. Pay special attention to: Why this problem is suitable for a sliding window (hint: positive integers). How the while loop triggers as soon as the window becomes valid (total >= target). Inside the while loop, how we first update the result (the minimum length) and then contract the window to see if a shorter valid subarray exists.
Code, Complexity, and Template
The key takeaway is that although there's a nested loop structure, the time complexity remains O(n). This is because the left and right pointers each traverse the array only once from left to right.
The Hello Interview article on this topic provides an excellent step-by-step motivation and a clean template to internalize.
Variable Length Sliding Window
To solidify your understanding, this article breaks down the variable-length pattern by starting from a naive solution and progressively optimizing it into the final sliding window algorithm.
Read the sections 'Naive Approach', 'The Sliding Window', 'Template', and 'When Do I Use This?'. Focus on how the logic evolves from brute-force to the efficient expand/contract model. The template provided is a powerful starting point for many problems. Estimated time: 10 minutes.
Conclusion
Today, we added the powerful sliding window technique to your algorithmic toolkit. It's a fundamental pattern for efficiently solving a wide range of subarray and substring problems that might otherwise require a brute-force O(n²) solution.
Key Takeaways:
- Core Idea: Use two pointers (
left,right) to maintain a "window" over the data, avoiding re-computation by sliding the window instead of rebuilding it. The result is an optimal O(n) time complexity. - Fixed-Length Window: Use when the problem specifies a subarray of size
k. The logic is to slide a window of constant size, adding one new element and removing one old element at each step. - Variable-Length Window: Use when searching for the longest or shortest subarray that meets a condition. The logic is to expand the window with the
rightpointer and contract it with theleftpointer whenever a certain validity condition is violated (or met, in minimization problems).
Preview of the Next Lesson
Having covered 1D arrays extensively, we will now move into two dimensions. In the next lesson, we will tackle matrix traversal and in-place manipulation problems. We will explore classic algorithms like spiral traversal and rotating a matrix, which are common questions in FAANG interviews and require a strong command of index manipulation and boundary conditions.