POST 1 of 5 MorningDSAConcept
Sliding window — the pattern for 'best subrange'
If you only learn one DSA pattern this week, learn sliding window. It solves more leetcode-medium problems than any other single technique, and the shape is small enough to memorise once and reach for forever. The setup — you have an array (or string) and you want the best subrange satisfying some constraint. Best could be longest, shortest, count of, max sum, anything. The brute force is O(n²) — enumerate all subranges, check each. The sliding window upgrade — keep two pointers, left and right, defining the current window. Expand from the right; shrink from the left when the window violates the constraint. Track the optimum window seen as you go. Key property — each element enters the window once (when right passes it) and leaves at most once (when left passes it). Total work — O(n). When does sliding window apply? Three signals. One — the goal is about a subarray or substring. 'Longest', 'shortest', 'count of', 'minimum window containing', etc. Two — the constraint is monotonic in window size. Adding to the window can only make the constraint 'better' or 'worse' in one direction. (Sum strictly grows when you add positive numbers; the count of distinct chars can only grow.) Three — each element is involved at most twice (entering, leaving). If you'd need to revisit elements multiple times, sliding window probably isn't the right tool. Variants. Fixed-size window. The window is exactly k wide; slide step by step. Useful for 'max sum of k consecutive elements'. Variable window. Grow and shrink based on the constraint. Useful for 'longest substring with at most k distinct chars'. The distinction matters because the loop structure differs slightly. Fixed-size — single for-loop, with the right edge auto-derived from left. Variable — while-loop or for-with-inner-while, expanding and shrinking. Memorise the shapes; the variants are tweaks.
#DSA#DataStructures#Algorithms#Python#100DaysOfCode#SlidingWindow