Skip to content
Array & StringBeginner

Sliding Window

Maintain a window of elements that slides across the array, expanding or shrinking to find optimal subarrays or substrings.

Problem: Maximum Sum Subarray of Size K

Find the maximum sum of any contiguous subarray of size 3 in [2, 1, 5, 1, 3, 2].

Start building window: add arr[0] = 2

Begin building our window of size 3. Current window sum = 2.

Window Sum: 2Max Sum: 0
Step 1/7
Speed:

When to Use

  • Find longest/shortest subarray with a property
  • Find substring with specific characters
  • Maximum/minimum sum of k consecutive elements
  • Contiguous subarray problems

Key Indicators

  • Contiguous subarray or substring
  • "Longest", "shortest", "maximum" in problem
  • Window size constraint
  • Character frequency in substring

Complexity

Time

O(n)

Space

O(1) or O(k)

Common Problems

Maximum Sum Subarray of Size KLongest Substring Without Repeating CharactersMinimum Window SubstringFruit Into Baskets

Code

left = 0
for right in range(n):
    add arr[right] to window
    while window is invalid:
        remove arr[left] from window
        left++
    update best result

Want all 29 patterns with detailed visual walkthroughs?

The complete book includes 84 practice problems, full decision tree, and illustrated step-by-step solutions.

Book Coming Soon ($4.99)