Sliding Window Algorithm – Fixed & Variable Length

Sliding Window Algorithm – Fixed & Variable Length

📌 When to Use Sliding Window

  • If a problem asks for:
    • Longest/shortest subarray with a condition
    • Fixed-length sum/subarray
    • Substring problems with characters/frequency
  • And constraints mention:
    • Positive integers or lowercase letters
    • Contiguous window
  • Then Sliding Window is your go-to strategy.

🔍 Keyword Clue: Subarray / Substring
🧠 Technique Hint: Start with two pointers → expand → shrink


🪟 Sliding Window Types

TypeUse Case ExampleWindow Behavior
Fixed LengthMax sum of k elementsAlways move right pointer k
Variable LengthLongest substring with at most 2 distinct charsExpand + shrink based on rule

🔒 Fixed-Length Window

Use when you’re given a fixed window size k and need to compute something over every window of size k.

✅ Constant time to slide window: +arr[i] - arr[i-k]
✅ Efficient for problems involving sums or frequency over exact-sized windows


🔓 Variable-Length Window

Use two pointers (start, end) to dynamically expand and shrink the window depending on conditions.

✅ Great for problems where you don’t know the window size up front
✅ Use when constraints say things like:

  • “at most K characters”
  • “longest subarray with sum ≤ target”
  • “substring with K distinct characters”

💡 Key Insight

When you see problems like:

  • “subarray”, “substring”
  • Sum, max/min, count
  • Length k, or conditions like “at most” or “exactly”

Think Sliding Window!


🧠 Sliding Window Patterns

PatternStrategy Description
Fixed window of size kSlide right pointer, remove left
Longest subarray with sumExpand with end, shrink with start
Substring with distinct charsUse hashmap to track frequency