"""Pattern 3: Sliding window.

Maintain a contiguous window [left, right]. Grow it by moving ``right``; when
the window breaks a rule (or satisfies it, for "minimum" questions), shrink
it from ``left``. Every index enters and leaves once, so the work is O(n).
"""

from collections import Counter


def longest_unique_substring(s: str) -> int:
    """Variable window, 'longest valid' flavour: shrink while invalid."""
    last_seen: dict[str, int] = {}
    left = best = 0
    for right, ch in enumerate(s):
        if ch in last_seen and last_seen[ch] >= left:
            left = last_seen[ch] + 1  # jump past the previous copy
        last_seen[ch] = right
        best = max(best, right - left + 1)
    return best


def min_subarray_len(target: int, nums: list[int]) -> int:
    """Variable window, 'shortest valid' flavour: shrink while still valid.

    Requires non-negative numbers (so growing never lowers the sum).
    """
    left = total = 0
    best = float("inf")
    for right, x in enumerate(nums):
        total += x
        while total >= target:
            best = min(best, right - left + 1)
            total -= nums[left]
            left += 1
    return 0 if best == float("inf") else int(best)


def min_window(s: str, t: str) -> str:
    """Smallest substring of s containing every character of t (with counts)."""
    need = Counter(t)
    missing = len(t)
    left = 0
    best = (0, float("inf"))
    for right, ch in enumerate(s):
        if need[ch] > 0:
            missing -= 1
        need[ch] -= 1
        while missing == 0:
            if right - left < best[1] - best[0]:
                best = (left, right)
            need[s[left]] += 1
            if need[s[left]] > 0:
                missing += 1
            left += 1
    return "" if best[1] == float("inf") else s[best[0] : int(best[1]) + 1]


def find_anagrams(s: str, p: str) -> list[int]:
    """Fixed-size window: start indices of anagrams of p in s."""
    k = len(p)
    if k > len(s):
        return []
    need = Counter(p)
    window = Counter(s[:k])
    hits = [0] if window == need else []
    for right in range(k, len(s)):
        window[s[right]] += 1
        window[s[right - k]] -= 1
        if window[s[right - k]] == 0:
            del window[s[right - k]]
        if window == need:
            hits.append(right - k + 1)
    return hits


def character_replacement(s: str, k: int) -> int:
    """Longest run of one letter after at most k replacements."""
    counts: Counter[str] = Counter()
    left = top = best = 0
    for right, ch in enumerate(s):
        counts[ch] += 1
        top = max(top, counts[ch])
        if right - left + 1 - top > k:
            counts[s[left]] -= 1
            left += 1
        best = max(best, right - left + 1)
    return best
