A sliding window is a technique used to process a subset of data in an array or string by maintaining a "window" of fixed or variable size that slides over the data, often to solve problems like finding subarrays, substrings, or optimizing computations.
Key Points:
Reduces time complexity by avoiding redundant computations.
Commonly used in problems involving contiguous subarrays or substrings.
Window size can be fixed (e.g., k elements) or dynamic (e.g., based on a condition).
Code Snippets:
1. Fixed-Size Sliding Window (e.g., Find maximum sum of k consecutive elements)
python
def max_sum_subarray(arr, k):
n = len(arr)
if n < k:
return None
# Initial window sum
window_sum = sum(arr[:k])
max_sum = window_sum
# Slide the window
for i in range(n - k):
window_sum = window_sum - arr[i] + arr[i + k] # Remove left, add right
max_sum = max(max_sum, window_sum)
return max_sum
# Example usage
arr = [1, 4, 2, 10, 23, 3, 1, 0, 20]
k = 4
print(max_sum_subarray(arr, k)) # Output: 39 (sum of [4, 2, 10, 23])
2. Variable-Size Sliding Window (e.g., Longest substring with at most k distinct characters)
python
from collections import defaultdict
def longest_substring_with_k_distinct(s, k):
if k == 0:
return 0
# Dictionary to store character counts
char_count = defaultdict(int)
max_length = 0
left = 0
# Slide the window
for right in range(len(s)):
char_count[s[right]] += 1
# Shrink window if more than k distinct characters
while len(char_count) > k:
char_count[s[left]] -= 1
if char_count[s[left]] == 0:
del char_count[s[left]]
left += 1
max_length = max(max_length, right - left + 1)
return max_length
# Example usage
s = "eceba"
k = 2
print(longest_substring_with_k_distinct(s, k)) # Output: 3 (substring "ece")
Summary:
Fixed-size: Window size is constant (e.g., sum of k elements).
Variable-size: Window size adjusts dynamically based on a condition (e.g., number of distinct characters).
Both use two pointers (left and right) to define the window boundaries.