DSA Crash Course
Templates

Template: 3. SLIDING WINDOW — Variable Size

Mark when done:

3. SLIDING WINDOW — Variable Size

# =============================================================================
# Use when: longest/shortest subarray with condition
def sliding_window_variable(arr, condition_fn):
    left = 0
    best = 0
    window = {}  # or any window state
    for right in range(len(arr)):
        # Expand: add arr[right] to window
        window[arr[right]] = window.get(arr[right], 0) + 1

        # Shrink: while window is invalid
        while not condition_fn(window):
            window[arr[left]] -= 1
            if window[arr[left]] == 0:
                del window[arr[left]]
            left += 1

        # Update answer (window is valid)
        best = max(best, right - left + 1)
    return best


# =============================================================================