AlgorithmsSliding Window

Sliding Window

Apply a window that slides over data to find subsets meeting a condition, useful for contiguous sequences.

Definition

A Sliding Window uses two pointers to track a sequence of elements in an array or string. The left and right pointers form a window that slides over the elements while analyzing its contents. This technique helps find patterns in sequential data, similar to how a magnifying glass reveals details as you move it across a page.

Fixed-Size Windows

These sliding windows maintain a constant size as they traverse through an array. The left and right pointers move together, and for each step, we add one new element and remove the oldest element. This pattern works well for finding patterns of fixed length, similar to how a ruler measures fixed distances as you slide it across a surface.

Fixed Window

def sliding_window_sums(self, nums: list[int], k: int) -> list[int]:
    result = []  # Store the sum of each window
    total = 0  # Current sum of the window
    
    # Add the first k numbers to the total sum
    for index in range(k):
        total += nums[index]
    
    result.append(total)  # Store the sum of the first window

    # Create left pointer at the beginning
    left = 0 
    
    # Create right pointer which always moves forward
    for right in range(k, len(nums)):  
        total += nums[right] # Add the number at the right pointer
        total -= nums[left] # Remove the number at the left pointer
        
        # Move the left pointer forward
        left += 1  

        # Store the new window sum
        result.append(total)  

    return result

In this example, we start by calculating the first window’s sum using the first k elements. Then as we slide through nums, we add the new element at right and remove the old element at left to maintain our window size. The left pointer follows behind the right pointer, keeping exactly k elements between them. This allows us to efficiently calculate each window’s sum without having to recalculate the entire window from scratch.

Dynamic Windows

Dynamic windows adjust their size by moving the left pointer based on certain conditions in the data. The left and right pointers move independently, and the window grows or shrinks depending on what elements it contains. This flexibility makes dynamic windows perfect for finding sequences that meet specific criteria, similar to how a camera lens adjusts until the image becomes clear.

Dynamic Window

def lengthOfLongestSubstring(self, s: str) -> int:
    # Create a set to keep track of window, 'res' to track result
    window = set()
    res = 0 

    # Create left pointer at the beginning, right pointer always moves forward
    left = 0
    for right in range(len(s)):
        # Get the current letter at the right pointer
        letter = s[right]

        # While the letter is in window, remove letter at left and shift it forward
        while letter in window:
            window.remove(s[left])
            left += 1
        
        # Add the current letter (at right pointer) to the window
        window.add(s[right])
    
        # Calculate the window size
        windowSize = right - left + 1

        # Update the result using the largest window size we've seen
        if windowSize > res:
            res = windowSize
    
    return res

We track unique characters using a set data structure for O(1) lookup time. When we find a duplicate, we shrink the window by moving left until the duplicate is gone. The right pointer always moves forward to grow the window, while left only moves to remove duplicates. At each step, we calculate the current window size using the formula right - left + 1 and keep track of the longest valid window we’ve seen.

How it Works

Sliding Window works by using two pointers to create and maintain a small section of elements. As we process the data, we gather information about elements in the current window to solve a specific problem. This technique is powerful because it allows us to process sequences efficiently by avoiding repeated calculations.


Most sliding window solutions follow a common pattern where the right pointer moves steadily forward using a for loop. The right pointer acts like a scout, moving one step at a time to explore new elements in the sequence. This steady forward movement helps us ensure we consider every possible window.


The left pointer, however, moves based on specific conditions in our problem. Sometimes it follows right away to maintain a fixed window size, other times it only moves when we need to shrink the window to maintain certain conditions. For example, when finding unique character sequences, left only moves when we need to remove duplicates from our window.

Sliding Window: Step-by-Step

1. Create the Window

Start with two pointers, left and right, typically at the beginning of the array or string. Initialize any additional variables needed to track information about your window (like a set or result variable).

2. Expand the Window

Move the right pointer forward one step at a time using a for loop. Add or process the new element at the right pointer position to update your window’s information.

3. Shrink if Needed

If the window breaks any conditions, move the left pointer forward to shrink the window. Remove or update information about elements that leave the window through the left pointer.

4. Update Result

After each window change, update your result if the current window is valid. Common updates include tracking the maximum window size, minimum sum, or storing valid windows in your result.
Common Patterns

Sliding Window patterns typically appear in problems involving sequences in arrays or strings. Look for problems that involve finding subarrays, counting elements, or calculating consecutive sequences. The key is recognizing when you need to process elements sequentially while maintaining information about a range of elements.


The moment a problem involves analyzing contiguous subarrays or finding patterns in sequential data, sliding window is likely the best approach. You might need to track sums, find unique elements, count frequencies, or detect specific patterns within your window. Whether it’s finding the longest substring of unique characters or the subarray with the largest sum, sliding window helps you efficiently process these sequences without unnecessary recalculations.

Best Practices

The Sliding Window technique is essential for solving array and string problems efficiently. When you spot a problem involving sequential data or subarrays, these practices will help you implement the optimal solution:


Choose the right data structure to track your window’s state. Use sets for unique elements, variables for sums, and hashmaps for frequency counting. Keep your state management simple and focused on what the problem needs.

Practice Problems
Sliding Window
Completed
Title
Notes
Solution
Medium
Medium
Medium
Hard
Hard

Copyright © StudyDSA. All rights reserved.