Shrink While Valid

Template

Use this when you need the smallest valid window.

for r = 0; r < n; r++:
    add nums[r]
 
    while window is valid:
        update min answer
        remove nums[l]
        l++

Problems Using This Pattern

Minimum Window Substring

Problem: find the shortest substring of s that contains all chars from t.

Valid: every needed char count is satisfied.

Minimum Size Subarray Sum

Problem: find the shortest positive-number subarray whose sum is at least target.

Valid: window_sum >= target.

Minimum Operations to Make Array Continuous

Problem: after sorting unique nums, keep the largest value range of size < n.

Valid: nums[r] - nums[l] < n.