pattern / MEDIUM
Process subarrays with a moving window
complexity
time
O(n)
space
O(1) or O(k) for the hashmap
02' — visual
interactive
Maximum sum subarray
03'
mental
model.
Imagine a window (defined by left and right pointers) that slides over the array. Expand the right pointer to add elements, shrink the left pointer to remove elements when a condition is violated.
Sliding Window is a technique used to perform operations on a contiguous subarray or substring of a given size within an array/string. The window slides over the data structure to find the optimal solution.
when to use ✓
when not ✗
04'
Problem involves contiguous subarray or substring
Asks for longest/shortest/maximum/minimum of something in a range
Brute force is O(n²) or O(n³)
Keywords: 'subarray', 'substring', 'window', 'contiguous'
05'
1# Beginner: Fixed-size sliding window2def max_sum_k(nums, k):3 n = len(nums)4 if n < k:5 return 06 window_sum = sum(nums[:k])7 max_sum = window_sum8 for i in range(k, n):9 window_sum += nums[i] - nums[i - k]10 max_sum = max(max_sum, window_sum)11 return max_sum
common mistakes
interview tips
06'
0 curated problems from LeetCode
No questions found for this pattern yet.
07'