Tensorum

Sliding Window

Fixed and variable windows for longest, shortest and counting subarray problems in linear time.

DSAIntermediate19 hrs7 patterns · 27 problems
0%
your progress

Core idea

Expand the right edge every step; shrink the left edge while the window is invalid. Each index enters and leaves once, so the whole scan is linear.

Reach for it when

  • Longest / shortest contiguous subarray or substring satisfying a constraint
  • Window validity only gets worse as it grows (or better as it shrinks)
  • Fixed size k windows with running aggregates

Template

def longest_unique(s):
    last, left, best = {}, 0, 0
    for right, ch in enumerate(s):
        if ch in last and last[ch] >= left:
            left = last[ch] + 1
        last[ch] = right
        best = max(best, right - left + 1)
    return best

Complexity

O(n) time, O(alphabet) or O(k) space.

Common pitfalls

  • Using it with negative numbers where validity isn't monotone (use prefix sums instead)
  • Updating the answer before the window is valid again
  • 'Exactly k' — compute atMost(k) − atMost(k−1)

Recognition cues

Fixed WindowLongestMinimumFrequency/HashingMonotonic Queue