AW Dev Rethought

βœ‚οΈ Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away - Antoine de Saint-ExupΓ©ry

🧩 Python DSA Patterns β€” Sliding Window πŸͺŸπŸ


Description:

The sliding window is a powerful algorithmic pattern for solving problems on contiguous arrays & strings.

Instead of recalculating values every time, you slide the window and update results incrementally β€” turning O(nΒ²) brute force into O(n).


πŸ“ Fixed-Size Window β€” Max Sum Subarray of Size k

We keep the sum of the first window of size k, then slide forward step by step: subtract the element going out, add the new one coming in.

def max_sum_subarray_k(arr, k):
    window_sum = sum(arr[:k])
    max_sum = window_sum

    for i in range(k, len(arr)):
        window_sum += arr[i] - arr[i-k]
        max_sum = max(max_sum, window_sum)

    return max_sum

print(max_sum_subarray_k([2, 1, 5, 1, 3, 2], 3))  # Output: 9

πŸ“ Variable-Size Window β€” Min Subarray Length β‰₯ Target

We expand the window until the sum β‰₯ target, then shrink it from the left to minimize length.

def min_subarray_len_at_least(target, arr):
    left = 0
    total = 0
    best = float("inf")

    for right in range(len(arr)):
        total += arr[right]
        while total >= target:
            best = min(best, right - left + 1)
            total -= arr[left]
            left += 1

    return 0 if best == float("inf") else best

print(min_subarray_len_at_least(7, [2, 3, 1, 2, 4, 3]))  # Output: 2

βœ… Takeaway

Sliding Window = reuse work from the previous step instead of recalculating.

Use it whenever the problem mentions contiguous subarrays or substrings.


πŸ‹οΈ Practice Problems

Try applying the Sliding Window pattern to these:

  1. Maximum Average Subarray I (LeetCode 643)
  2. Longest Substring Without Repeating Characters (LeetCode 3)
  3. Minimum Size Subarray Sum (LeetCode 209)

πŸ“‚ Full Script

The blog covers the essentials β€” find the complete notebook with all snippets & extras on GitHub Repo πŸ‘‰ Python DSA Patterns


Link copied!

Comments

Add Your Comment

Comment Added!