Sliding Window Pattern
Sliding Window
Problem Scenario / Typical Use Case
Imagine you are analyzing hourly traffic data on a website for a week, and you want to find the maximum number of visitors in any 3-hour period.
Checking every possible 3-hour window by summing the visitors repeatedly is inefficient for large datasets. The Sliding Window pattern allows you to maintain a running calculation over a fixed or dynamic range, updating it as the window “slides” through the dataset.
Basic Idea
The Sliding Window pattern involves maintaining a subset (window) of elements and moving it through a sequence to compute results efficiently:
- Fixed-size window: slide the window step by step, updating the calculation incrementally.
- Variable-size window: expand or shrink the window based on conditions (e.g., sum, max, unique elements).
In variable-size windows, the pattern is often implemented using two pointers that mark the dynamic start and end of the window
Sliding Window can efficiently solve problems involving continuous segments or substrings, such as:
- Maximum or minimum in a subarray.
- Sum of elements over a fixed range.
- Longest/shortest substring with certain properties.
- Detecting patterns in time-series data.
Advantages
- Efficiency: Avoids recalculating the sum or property for overlapping portions of the sequence.
- Flexibility: Works with both fixed and variable window sizes.
- Clarity: Logical movement of the window aligns naturally with many real-world sequential problems.
Limitations / Considerations
- Works best on linear sequences (arrays, strings, time series).
- Complexity can increase if the condition inside the window is complex (e.g., requires additional data structures like heaps or hashmaps).
- Careful handling of boundaries is required to avoid off-by-one errors.
- If the property inside the window cannot be updated incrementally (e.g., median), additional data structures may be needed.
Practical Examples / Thought Triggers
- Maximum Website Visitors in 3-Hour Windows: Maintain a running sum, adding the next hour and removing the first hour of the window.
- Longest Substring Without Repeating Characters: Expand window until a duplicate is found, then shrink from the left until unique again.
- Minimum Length Subarray with Target Sum: Dynamically adjust window size to satisfy the condition while maintaining minimal length.
Thought Triggers:
- Is the window size fixed or dynamic? This decision changes the implementation approach.
- Can this be combined with Two Pointers for variable-size ranges?
- Does the window calculation require extra structures like hashmaps or heaps for efficiency?
Implementation Example
Here’s a Python example for maximum sum of a fixed-size sliding window:
def max_sum_subarray(arr, k):
if len(arr) < k:
return None
window_sum = sum(arr[:k])
max_sum = window_sum
for i in range(k, len(arr)):
window_sum += arr[i] - arr[i - k] # slide window
max_sum = max(max_sum, window_sum)
return max_sum
# Example usage
visitors = [10, 20, 30, 40, 50, 60, 70]
window_size = 3
print(max_sum_subarray(visitors, window_size))
# Output: 180 (sum of [50, 60, 70])
This illustrates the core principle: reuse previous calculations and update incrementally as the window slides. The algorithm runs in time and space, as each element is processed exactly once
Related Articles
- Two Pointers: Sliding Window is often implemented with two pointers marking the start and end of the window.
- Prefix Sum: Can be combined to compute sums or averages in time per window.
- Hashmaps / Frequency Counting: Useful when tracking counts or unique elements within the window.