The Sliding Window is an algorithmic technique used for efficiently processing sub-sequences (like sub-arrays or substrings) within a linear data structure (arrays, strings, lists).
It involves maintaining a "window" of elements that slides across the data, typically by expanding its right boundary and contracting its left boundary, to find optimal sub-sequences that meet a specific condition. Its efficiency comes from avoiding redundant calculations by re-using previous computations as the window moves, often turning O(N*M) or O(N^2) brute-force solutions into O(N) linear time solutions.
Code Snippets to Illustrate
1. Fixed-Size Sliding Window: Maximum Sum Subarray of Size k
Problem: Given an array of integers and an integer k, find the maximum sum of any contiguous subarray of size k.
def max_sum_subarray_fixed_size(arr, k):
if not arr or k <= 0 or k > len(arr):
return 0 # Handle edge cases
window_sum = 0
max_sum = float('-inf') # Initialize with negative infinity
# Calculate sum of the first window
for i in range(k):
window_sum += arr[i]
max_sum = window_sum
# Slide the window across the array
# 'i' represents the right end of the current window
for i in range(k, len(arr)):
# Subtract the element leaving the window (arr[i-k])
# Add the new element entering the window (arr[i])
window_sum = window_sum - arr[i - k] + arr[i]
max_sum = max(max_sum, window_sum)
return max_sum
# Example Usage:
arr1 = [2, 1, 5, 1, 3, 2]
k1 = 3
print(f"Max sum subarray of size {k1} in {arr1}: {max_sum_subarray_fixed_size(arr1, k1)}") # Output: 9 (from [5, 1, 3])
arr2 = [1, 2, 3, 4, 5]
k2 = 2
print(f"Max sum subarray of size {k2} in {arr2}: {max_sum_subarray_fixed_size(arr2, k2)}") # Output: 9 (from [4, 5])
Explanation:
- We calculate the sum of the first
k elements to establish the initial window.
- Then, as we slide the window to the right, instead of re-summing all
k elements, we simply subtract the element that falls out of the window on the left and add the new element that enters the window on the right. This keeps the sum updated in O(1) time per step, leading to an overall O(N) solution.
2. Variable-Size Sliding Window: Longest Substring Without Repeating Characters
Problem: Given a string s, find the length of the longest substring without repeating characters.
def length_of_longest_substring(s: str) -> int:
char_index_map = {} # Stores character -> its last seen index
max_length = 0
window_start = 0 # Left pointer of the window
# Iterate with window_end as the right pointer
for window_end in range(len(s)):
right_char = s[window_end]
# If the character is already in the map AND
# its last seen index is within the current window (>= window_start)
# This means we have a repeating character.
if right_char in char_index_map and char_index_map[right_char] >= window_start:
# Move the window_start past the last occurrence of the repeating character
window_start = char_index_map[right_char] + 1
# Update the character's last seen index
char_index_map[right_char] = window_end
# Calculate the current window length and update max_length
max_length = max(max_length, window_end - window_start + 1)
return max_length
# Example Usage:
s1 = "abcabcbb"
print(f"Longest substring without repeating chars in '{s1}': {length_of_longest_substring(s1)}") # Output: 3 (abc)
s2 = "bbbbb"
print(f"Longest substring without repeating chars in '{s2}': {length_of_longest_substring(s2)}") # Output: 1 (b)
s3 = "pwwkew"
print(f"Longest substring without repeating chars in '{s3}': {length_of_longest_substring(s3)}") # Output: 3 (wke)
Explanation:
- We use
window_start and window_end pointers to define the current window.
- A
char_index_map keeps track of the last seen index of each character within the current window.
- As
window_end moves, we add s[window_end] to our window.
- If
s[window_end] is already present in char_index_map and its last occurrence (char_index_map[right_char]) is within or at the window_start, it means we've found a repeat. To resolve this, we shrink the window from the left by moving window_start to char_index_map[right_char] + 1. This ensures the window only contains unique characters.
- We continuously update
max_length with the size of the valid window (window_end - window_start + 1).
This allows us to solve the problem in O(N) time.